[英]Java 8 stream filter for Map<String, List<Object>>
當我嘗試使用流來處理地圖時,我遇到了問題。 我有 :
Class Person {
public String name;
public String ID;
}
和 2 個不同的地圖(相同的結構但包含不同的元素):
Map<String, List<Person>> map1 = new HashMap<>();
map1.put("group1", new Person("abc", "12345"));
map1.put("group2", new Person("def", "23456"));
和
Map<String, List<Person>> map2 = new HashMap<>();
map2.put("group3", new Person("asd", "12345"));
我想要做的是使用流來處理這兩個地圖,並過濾掉只滿足我給定條件的 Map<String, List> ,例如,如果 Person 具有相同的 ID,則合並它並保留名字。 對於上面的例子,結果應該是:
{group1,("abc", "12345")}
{group2,("def", "23456")}
這是我目前的實現:
Map<String, List<Person>> result = map1.entrySet()
.stream()
.filter(x -> x.getValue().stream().allMatch(e -> e.getID() !=
map2.entrySet().stream().flatMap(it -> it.getValue().stream().forEach(y -> y.getID()))))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
我不熟悉 Stream,任何幫助表示贊賞。
謝謝
您是否在追求以下內容?
Map<String, List<Person>> map1 = new HashMap<>();
map1.put("group1", new ArrayList<>(List.of(new Person("abc", "12345"))));
map1.put("group2", new ArrayList<>(List.of(new Person("def", "23456"))));
Map<String, List<Person>> map2 = new HashMap<>();
map2.put("group3", new ArrayList<>(List.of(new Person("asd", "12345"))));
Map<String, List<Person>> mergedMap = new HashMap<>(map1);
for (Entry<String, List<Person>> entry : map2.entrySet()) {
for (Person p2 : entry.getValue()) {
boolean sameIdFound = map1.entrySet()
.stream()
.anyMatch(e1 -> e1.getValue().stream().anyMatch(p1 -> p1.getId().equals(p2.getId())));
if (! sameIdFound) {
mergedMap.computeIfAbsent(entry.getKey(), k -> new ArrayList<>())
.add(p2);
}
}
}
mergedMap.forEach((g, pl) -> System.out.println(g + " -> " + pl));
輸出:
group2 -> [23456=def] group1 -> [12345=abc]
我首先創建一個與map1
相同的新地圖(淺拷貝,你可能想要一個更深的副本,現在留給你)。 接下來,對於map2
某個地方的每個人,我檢查map1
已經存在具有相同 ID 的人。 如果沒有,我將它與來自map2
的組和名稱一起插入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.