在地图上过滤 [英] Filter on map of map

查看:145
本文介绍了在地图上过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的地图地图,想要根据值过滤它。结果应该分配回同一个地图。请知道最佳方法是什么。

I have below map of map and want to filter it based on a value. The result should be assigned back to same map. Please let know what is the best approach for this.

Map<String, Map<String, Employee>> employeeMap;

<
 dep1, <"empid11", employee11> <"empid12",employee12>
 dep2, <"empid21", employee21> <"empid22",employee22>
>

Filter: employee.getState="MI"

我试过以下但是我无法访问员工对象

I tried like below but i was not able to access the employee object

currentMap = currentMap.entrySet().stream()
            **.filter(p->p.getValue().getState().equals("MI"))**                    
            .collect(Collectors.toMap(p -> p.getKey(),p->p.getValue()));


推荐答案

如果你想修改地图(和,它允许这样),您可以使用 forEach 迭代地图的条目,然后使用 removeIf for内部映射的每个值用于删除满足谓词的员工:

If you want to modify the map in place (and that it allows so), you can use forEach to iterate over the entries of the map, and then use removeIf for each values of the inner maps to remove the employees that satisfy the predicate:

employeeMap.forEach((k, v) -> v.values().removeIf(e -> e.getState().equals("MI")));

否则,你可以做的是使用 toMap collector,其中映射值的函数负责通过迭代内部映射的条目集来删除相关员工:

Otherwise, what you can do is to use the toMap collector, where the function to map the values takes care of removing the concerned employees by iterating over the entry set of the inner maps:

Map<String, Map<String, Employee>> employeeMap =
    employeeMap.entrySet()
               .stream()
               .collect(toMap(Map.Entry::getKey,
                              e -> e.getValue().entrySet().stream().filter(emp -> !emp.getValue().getState().equals("MI")).collect(toMap(Map.Entry::getKey, Map.Entry::getValue))));

这篇关于在地图上过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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