簡體   English   中英

過濾Java 8 Streams中的Map

[英]filter Map in Java 8 Streams

我試圖使用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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM