Home » Java » filter Map in Java 8 Streams

filter Map in Java 8 Streams

Posted by: admin December 28, 2021 Leave a comment

Questions:

I was trying to filter Entries in HashMap using Streams API, but stuck in last method call Collectors.toMap. So, I don’t have clue to implemement toMap method

    public void filterStudents(Map<Integer, Student> studentsMap){
            HashMap<Integer, Student> filteredStudentsMap = studentsMap.entrySet().stream().
            filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi")).
            collect(Collectors.toMap(k , v));
    }

public class Student {

        private int id;

        private String firstName;

        private String lastName;

        private String address;
    ...

    }

Any Suggestions?

Answers:

Just generate the output Map out of the key and value of the entries that pass your filter:

public void filterStudents(Map<Integer, Student> studentsMap){
    Map<Integer, Student> filteredStudentsMap = 
        studentsMap.entrySet()
                   .stream()
                   .filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi"))
                   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}