Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
  .toList();

And then use the code above.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading