Java 8过滤器映射< String,List< Employee>> [英] Java 8 Filter Map<String,List<Employee>>

查看:84
本文介绍了Java 8过滤器映射< 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过滤器映射&lt; String,List&lt; Employee&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆