java - 将对象列表转换为通过检查的整数列表
问题描述
我想按顺序得到一个小于 5 的值List
。Integer
我该怎么做?
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);
解决方案
鉴于并非映射的所有值都是整数,您需要首先检查元素是否是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);
推荐阅读
- ios - SwiftUI ZStack 采用所有屏幕高度,但应该是固定高度
- r - 为什么使用矢量从函数内渲染 Rmarkdown 文件时 df 的布局会发生变化?
- javascript - 为什么'react-hook-form'给出空数据?
- sqlite - Haskell:在 Yesod 测试中使用内存中的 sqlite db?
- terraform - Terraform - 如何使用每个 'terraform apply' 重新创建 'local_file' 资源
- mysql - Rails 4.2.7.1 中的 ActiveRecord::StatementInvalid
- javascript - 单击按钮后如何重置值?
- powerbi - DAX - 计算哪个项目具有最大值
- r - 将txt文件转换为矢量
- apostrophe-cms - 如何修剪 aposDocVersion 表