Ankit Ankit - 1 year ago 68
Java Question

filter Map in Java 8 Streams

I was trying to filter Entries in HashMap using Streams API, but stuck in last method call

. 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?

Answer Source

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 = 
                   .filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi"))
                   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download