过滤Java 8 Streams中的Map

Ank*_*kit 6 java hashmap java-8 java-stream

我试图使用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;
    ...

    }
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Era*_*ran 13

只需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));
}
Run Code Online (Sandbox Code Playgroud)

  • @Ankit您想使用必要的最简单的接口.如果它是一个HashMap(它将是),应该没关系,但是如果你需要像LinkedHashMap这样的特定实现,那么你需要使用4个参数来映射/sf/ask/2036319421/ -tomap - 从列表,如何对保的阶 (2认同)