filter Map in Java 8 Streams

Ankit :

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?

Eran :

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));
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465433&siteId=1