【问题标题】:transform a list of objects into a list of integers that pass a check将对象列表转换为通过检查的整数列表
【发布时间】:2018-12-13 17:02:05
【问题描述】:

我想按顺序获得 Integers 中的 List,其值小于 5。

我该怎么做?

TreeMap<String,Object> treeMap = new TreeMap<String,Object>();
HashMap<String,Object> map1 = new HashMap<String,Object>();

map1.put("a",1);
map1.put("b","2x");
map1.put("c",5);
map1.put("d",3);
map1.put("e",2);

List<Object> x = new ArrayList<>();

x = map1.values()
       .stream()
       .collect(Collectors.toList());

x.forEach(System.out::println);

【问题讨论】:

  • 你被困在哪里了? TreeMap 在哪里被使用?并避免使用Object 处理所有内容。
  • 我投票决定将此问题作为离题结束,因为这似乎是一个家庭作业问题,并且 OP 几乎没有尝试。

标签: java java-8 hashmap java-stream


【解决方案1】:

鉴于并非映射的所有值都是整数,您需要首先检查元素是否为Integer,然后对其进行映射,然后检查它是否小于 5,如果是,则打印该元素。

map1.values()
    .stream()
    .filter(e -> e instanceof Integer) // is this number an integer? if yes then you can pass else no
    .map(e -> (Integer)e) // map to integer so we can compare with '<' symbol
    .filter(e -> e < 5) 
    .forEach(System.out::println);

【讨论】:

  • .filter(e -&gt; (e instanceof Integer) ? ((Integer) e).intValue() &lt; 5 : false
  • @daniu nice!... 或者更好的.filter(e -&gt; (e instanceof Integer) &amp;&amp; (Integer) e &lt; 5),但我更喜欢通过使用多个中间操作来保持简单。
【解决方案2】:

其他答案似乎没有满足您的部分要求:

Integers 中的List,按顺序

所以我会解决这个问题:

List<Integer> sortedList = 
    map1.values ()
        .stream () 
        .filter (Integer.class::isInstance) // keep only Integers
        .map (Integer.class::cast) // cast to Integer
        .filter (i -> i < 5) // keep only values < 5
        .sorted () // sort
        .collect(Collectors.toList()); // collect into a List
System.out.println (sortedList);

输出:

[1, 2, 3]

您还可以生成int 数组而不是List&lt;Integer&gt;

int[] sortedArray = 
    map1.values ()
        .stream () 
        .filter (Integer.class::isInstance)
        .mapToInt (Integer.class::cast)
        .filter (i -> i < 5)
        .sorted ()
        .toArray();

输出:

[1, 2, 3]

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2021-08-08
    • 2013-12-02
    • 2011-02-19
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多