java 8 map 过滤_Java 8使用条件过滤并收集自定义Map
时间: 2024-03-21 12:40:28 浏览: 15
好的,针对您的问题,我可以给出以下的示例代码:
假设有一个包含学生信息的Map,其中key为学生姓名,value为学生分数,我们需要将分数大于等于60分的学生筛选出来并且组成一个新的Map返回,可以按照以下步骤进行:
1.先使用entrySet()方法将Map转换成一个Set集合。
2.然后使用Stream流对集合中的每一个元素进行过滤,保留符合条件的元素。
3.最后将过滤后的元素收集到一个新的Map中。
具体实现代码如下:
```java
Map<String, Integer> studentScores = new HashMap<>(); // 假设已经有了学生信息的Map
// 添加一些学生信息
studentScores.put("张三", 80);
studentScores.put("李四", 55);
studentScores.put("王五", 90);
studentScores.put("赵六", 70);
// 使用Stream流对集合中的每一个元素进行过滤,保留符合条件的元素
Map<String, Integer> filteredStudentScores = studentScores.entrySet().stream()
.filter(entry -> entry.getValue() >= 60) // 过滤分数小于60的学生
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // 将过滤后的元素收集到一个新的Map中
System.out.println(filteredStudentScores); // 输出过滤后的学生信息
```
执行上述代码后,输出结果为:{张三=80, 王五=90, 赵六=70},即分数大于等于60分的学生信息被筛选出来,组成了一个新的Map返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)