Search code examples
java-8java-stream

Java 8 - using streams to get a submap of a map


Java 8

Given

Set<String> set_dept_law = *a set of specific departments*

Map<String,List<Employee>> map_empl_by_dept = *a map of all employees keyed by department*

How do I use streams to get a map of all employees in all the law departments? I've tried things along these lines:

Map<String,List<String>> map_empl_law_dept = map_empl_by_dept.stream().filter( e -> set_dept_law.contains( e.getKey())).collect( Collectors.toMap));

without much luck.

TIA,

Still-Learning Steve


Solution

  • You can try this

    Map<Integer, List<String>> result = map.entrySet().stream()
        .filter(e -> set.contains( e.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));