如何过滤 Map<String,Map<String,Employee>>
使用 Java 8 过滤器?
只有当列表中的任何员工具有字段值 Gender = "M"时,我才需要进行过滤。
输入:
Map<String,Map<String,Employee>>
输出:
Map<String,Map<String,Employee>>
过滤条件:
Employee.genter = "M"
如果过滤结果为空,我还必须返回空 map 。
我尝试了下面的方法,但它没有按预期工作。只有当所有员工的性别都是“M”时,它才会返回。
tempCollection.entrySet().stream()
.filter(i -> i.getValue().entrySet().stream().allMatch(e-> "M".equals(e.getValue().getGender())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
最佳答案
您可以简单地迭代键值对并过滤为:
Map<String, Map<String, Employee>> output = new HashMap<>();
tempCollection.forEach((k, v) -> {
if (v.values().stream().anyMatch(i -> "M".equals(i.getGender()))) {
output.put(k, v.entrySet()
.stream()
.filter(i -> "M".equals(i.getValue().getGender()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue)));
}
});
关于Java 8 Stream filter map in map -- Map<String,Map<String,Employee>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927656/