[英]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.