Java 8中的流过滤和映射

8

我正在尝试使用Stream 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;
    ...

    }

有什么建议吗?

2
只是为了让您清楚。Collectors.toMap中的每个参数都需要一个函数,因此k和v不存在。它应该是toMap(s -> s.getKey(), s -> s.getValue()),可以像@Eran的答案中那样转换为方法引用。即使它们有点长,我仍然建议这样做。 - Novaterata
1
你可能想阅读这个问题以及它所标记的重复问题 https://dev59.com/9HI-5IYBdhLWcg3wKE6x - Novaterata
1个回答

16

只需从通过筛选的条目的键和值中生成输出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));
}

我需要将结果映射转换为 HashMap<Integer,Student> 吗? - Ankit
1
@Ankit 你是在问结果是否会是HashMap,还是在问如何确保结果是HashMap?Collectors.toMap的两个参数变体返回一个Map。还有其他变体,可以指定要创建的Map类型。 - Eran
2
@Ankit,你应该使用最简单的接口。它不应该关心它是一个HashMap(实际上就是),但如果你需要一个特定的实现,比如LinkedHashMap,那么你需要使用4个参数的toMap方法。https://dev59.com/KF4b5IYBdhLWcg3wdxgv - Novaterata
@Eran:我一直在遇到编译错误“类型不匹配:无法将Map<Object,Object>转换为HashMap<Integer,Student>”。现在,经过强制转换后,一切都正常了。谢谢。 - Ankit
@Ankit,不要使用HashMap<Integer,Student>获取结果,使用Map<Integer,Student>获取它。这样就不需要进行任何转换了。 - Jagannath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接