[英]Merge two collections in Java
我有兩張地圖:
Map<String, Student> students1 = new HashMap<>();
students1.put("New York", new Student("John"));
students1.put("Canada", new Student("Robert"));
Map<String, Student> students2 = new HashMap<>();
students2.put("Chicago", new Student("Nick"));
students2.put("New York", new Student("Ann"));
結果,我想得到這個:
{Canada=Robert, New York=[John, Ann], Chicago=Nick}
我可以輕松地這樣做:
Map<City, List<Student>> allStudents = new HashMap<>();
students1.forEach((currentCity, currentStudent) -> {
allStudents.computeIfPresent(currentCity, (city, studentsInCity) -> {
studentsInCity.add(currentStudent);
return studentsInCity;
});
allStudents.putIfAbsent(currentCity, new ArrayList<Student>() {
{
add(currentStudent);
}
});
});
// then again for the second list
但是有沒有其他方法可以合並許多集合(在這種情況下是兩個)? 是否有類似簡短的 lambda 表達式,或來自某些集成 Java 庫的方法等...?
您可以在任意數量的地圖上創建一個流,然后在它們的條目上創建平面地圖。 然后就像按條目的鍵分組一樣簡單,將條目的值映射到List
作為值:
Map<String, List<Student>> collect = Stream.of(students1, students2)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
使用靜態導入以提高可讀性:
Map<String, List<Student>> collect = Stream.of(students1, students2)
.flatMap(map -> map.entrySet().stream())
.collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));
替換toList()
與toSet()
如果一個Set
是作為地圖的值比較合適。
我認為 Magilex 提供的Stream
版本是最優雅的方式。 但我還是想再給一個選擇。
static final Function<...> NEW_LIST = __ -> new ArrayList<>();
Map<City, List<Student>> allStudents = new HashMap<>();
students1.forEach((city, student) -> {
allStudents.computeIfAbsent(city, NEW_LIST).add(student);
});
https://www.baeldung.com/java-merge-maps這是一個鏈接,應該會有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.