Java 8过滤器映射< String,List< Employee>> [英] Java 8 Filter Map<String,List<Employee>>
问题描述
如何使用Java 8筛选器筛选Map<String, List<Employee>>
?
How to filter a Map<String, List<Employee>>
using Java 8 Filter?
仅当列表中的任何员工的字段值为Gender = "M"
时,我才需要过滤.
I have to filter only when any of employee in the list having a field value Gender = "M"
.
输入:Map<String,List<Employee>>
输出:Map<String,List<Employee>>
过滤条件:Employee.genter = "M"
Input: Map<String,List<Employee>>
Output: Map<String,List<Employee>>
Filter criteria: Employee.genter = "M"
如果List
Also i have to filter out the key in the output map (or filter map [new map we get after filter]) if the List<> is empty on the map value
推荐答案
要过滤掉条目,其中列表中包含不属于"M"
性别的雇员:
To filter out entries where a list contains an employee who is not of the "M"
gender:
Map<String, List<Employee>> r2 = map.entrySet().stream()
.filter(i -> i.getValue().stream().allMatch(e-> "M".equals(e.gender)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
要过滤掉不属于"M"
性别的雇员:
To filter out employees who are not of the "M"
gender:
Map<String, List<Employee>> r1 = map.entrySet().stream()
.filter(i -> !i.getValue().isEmpty())
.collect(Collectors.toMap(Map.Entry::getKey,
i -> i.getValue().stream()
.filter(e -> "M".equals(e.gender)).collect(Collectors.toList())));
要过滤掉列表中不包含任何"M"
雇员的条目.
To filter out entries where a list doesn't contain any "M"
employee.
Map<String, List<Employee>> r3 = map.entrySet().stream()
.filter(i -> i.getValue().stream().anyMatch(e -> "M".equals(e.gender)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
让我们在地图上有2个条目:
Let's have 2 entries in the map:
"1" -> ["M", "M", "M"]
"2" -> ["M", "F", "M"]
他们的结果将是:
r1 = {1=[M, M, M], 2=[M, M]}
r2 = {1=[M, M, M]}
r3 = {1=[M, M, M], 2=[M, F, M]}
这篇关于Java 8过滤器映射< String,List< Employee>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!