过滤地图列表元素,然后在Java 8+中返回地图

时间:2019-09-19 00:15:00

标签: java

我想过滤地图列表的元素,然后在Java 8+中返回地图

public class Test {
    List<Employee> list1 = new ArrayList<>();
    list1.add(emp1);                   // emp1's  filterEmployee return true    
    list1.add(emp2);                   // emp2's  filterEmployee return true  
    list1.add(emp3);                   // emp3's  filterEmployee return false  

    List<Employee> list2 = new ArrayList<>();
    list2.add(emp4);                    // emp4's  filterEmployee return false        
    list2.add(emp5);                    // emp5's  filterEmployee return true 
    list2.add(emp6);                    // emp6's  filterEmployee return true 

    map.put("Sales", list1);
    map.put("Tech", list2);



    public Map<Department, List<Employee>> getEmployeeByDepartment( Map<Department, List<Employee>> map)
    {
        return map1;
    }   

    static boolean filterEmployee(Employee employee)
    {
        check employee something and filter out based on some critiea
        and return true or false based on that
    }
}

在getEmployeeByDepartment方法中,对于地图中的每个条目,    通过使用下面的filterEmployee方法在地图值列表中过滤雇员,返回的map1将包含这样的地图,即

<“ Sales”,list1.add(emp1)> // emp1的filterEmployee返回true

<“ Sales”,list1.add(emp2)> // emp2的filterEmployee返回true

<“ Tech”,list2.add(emp5)> // emp5的filterEmployee返回true

<“ Tech”,list2.add(emp6)> // emp6的filterEmployee返回true

我一直在尝试这种方法,但是没有用

Map<Department, List<Employee>> map2 = map.entrySet().stream().filter(entry -> entry.getValue().stream().filter(Test::filterEmployee).collect(Collectors.toMap((Department)entry.getKey(), (List<Employee>)entry.getValue())));

2 个答案:

答案 0 :(得分:2)

假设

Predicate<Employee> test;
Map<Department,List<Employee>> map;

您有几种选择:

对地图的就地更改:

map.values().forEach(el -> el.removeIf(Predicate.not(test)));

插入新地图:

Map<Department,List<Employee>> result = new HashMap<>();
map.forEach((d, el) -> result.put(d, el.stream().filter(test).collect(toList()));

通过流处理创建:

Map<Department,List<Employee>> result = map.keySet().stream()
    .collect(toMap(d -> d, d -> map.get(d).stream().filter(test).collect(toList())));

还有其他选择,但是最明显的选择。

答案 1 :(得分:1)

类似的事情应该起作用:

private static boolean shouldKeep(Employee employee) { ... }

// ...

Map<Department, List<Employee>> employees = // a map you've built

// ...

Map<Department, List<Employee>> filteredMap =
                employees.entrySet().stream().collect(
                        Collectors.toMap(
                                e -> e.getKey(),
                                e -> e.getValue().stream()
                                        .filter(employee -> shouldKeep(employee))
                                        .collect(Collectors.toList())));