Search code examples
javajava-stream

Java 8: How to filter the map from a list of list Ids and generate new List using Streams


Firstly This is not a duplicate question.

I have list of List<Integer> and Map of Integer Ids and Employee Object as below:

List<List<Integer>> ids=new ArrayList<new ArrayList<Integer>>();
ids.add(Arrays.asList(1,2));
ids.add(Arrays.asList(2,3));

Map<Integer, Employee> employeesByEmployeeId=new HashMap();
employeesByEmployeeId.put(1,new Employee("Test"));
employeesByEmployeeId.put(2,new Employee("Test1"));
employeesByEmployeeId.put(3,new Employee("Test2"));
employeesByEmployeeId.put(4,new Employee("Test3"));

Now I have to fetch list of Employee whose Ids are present in ids list.

Result

[Employee("Test"),Employee("Test1"),Employee("Test2")]

Solution which is not complete--

List<List<EmployeDTO>> employeeDto=data.getEmployee().stream().map(EmployeeDto::getSubEmployee).toList();
Set<Set<Integer>> ids=employeeDto.stream().map(employee -> employee.stream().map(EmployeeDto::getIds).collect(Collectors.toSet()));
            

Note: this is a dummy data


Solution

  • Stream the Map's entrySet, filter using a Predicate, map to get the Entry's value, then collect:

    List<Employee> filteredList = employeesByEmployeeId.entrySet().stream()
      .filter(e -> ids.contains(e.getKey()))
      .map(e -> e.getValue())   //or Entry::getValue
      .toList();
    

    EDIT:

    Since you changed your requirements around, first convert your List<List<Integer>> to a List<Integer>like this:

    List<List<Integer>> idLists= new ArrayList<>();
    idLists.add(List.of(1,2));
    idLists.add(List.of(2,3));
    
    List<Integer> ids = idLists.stream()
      .flatMap(List::stream)
      .distinct()
      .toList();
    

    And then use the code above.