首页 > 解决方案 > 将对象列表转换为通过检查的整数列表

问题描述

我想按顺序得到一个小于 5 的值ListInteger

我该怎么做?

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);

标签: javajava-8hashmapjava-stream

解决方案


鉴于并非映射的所有值都是整数,您需要首先检查元素是否是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);

推荐阅读