我尝试使用 Streams API 过滤 HashMap 中的条目,但卡在了最后一个方法调用 Collectors.toMap
中。所以,我不知道如何实现 toMap 方法
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;
...
}
有什么建议吗?
最佳答案
只需根据通过过滤器的条目的键和值生成输出 Map
:
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));
}
关于java - Java 8 Streams 中的过滤映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45328544/