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 studentsMap){
HashMap 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?
解决方案
Just generate the output Map out of the key and value of the entries that pass your filter:
public void filterStudents(Map studentsMap){
Map filteredStudentsMap =
studentsMap.entrySet()
.stream()
.filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}