Java 从多个贴图中获取重复贴图键的列表
我有多个数组的映射Java 从多个贴图中获取重复贴图键的列表,java,java-stream,Java,Java Stream,我有多个数组的映射 Map<String, List<String>> map1 = new HashMap<>(); Map<String, List<String>> map2 = new HashMap<>(); Map<String, List<String>> map3 = new HashMap<>(); Map<String, List<String>>
Map<String, List<String>> map1 = new HashMap<>();
Map<String, List<String>> map2 = new HashMap<>();
Map<String, List<String>> map3 = new HashMap<>();
Map<String, List<String>> map4 = new HashMap<>();
除了遍历所有映射键、检查集合是否包含键以及如果不向集合中添加键之外,我想不出任何更干净的方法来实现这一点。有没有一种方法可以通过streams实现这一点?因为您使用的是java stream标记,所以您可以这样解决您的问题:
Set<String> duplicateKeys = Stream.of(map1.keySet(), map2.keySet(), map3.keySet(), map4.keySet(), map5.keySet())
.flatMap(Set::stream)
.collect(Collectors.toMap(Function.identity(), x -> false, (a, b) -> true))
.entrySet().stream()
.filter(Map.Entry::getValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
.collect(Collectors.toMap(Function.identity(),x->false,(a,b)->true))
这个函数返回一个Map
它返回键true
如果重复和false
如果没有,那么您只需过滤以获得值为true的条目.filter(Map.Entry::getValue)
表示重复的。@SafeVarargs
@SafeVarargs
private static Set<String> findDuplicateKeys(Map<String, ?>... maps) {
Set<String> keys = new HashSet<>();
return Arrays.stream(maps)
.flatMap(map -> map.keySet().stream())
.filter(key -> !keys.add(key))
.collect(Collectors.toSet());
}
私有静态集FindDuplicateKey(映射…映射){
Set keys=new HashSet();
返回数组.stream(映射)
.flatMap(map->map.keySet().stream())
.filter(键->!键。添加(键))
.collect(收集器.toSet());
}
我会将结果建模为一个集合而不是列表,因为不可能有重复的元素。或者,您可以试试这个。创建映射流,然后
flatMap
将其映射到键流,然后将键收集到Map
中,计算每个键的数量,然后流式处理该入口集,Set
,根据键出现的计数进行过滤,将其映射到键值并收集到列表。这应该能够与.parallel()
一起运行
私有列表查找(映射…映射){
返回数组.asList(maps).stream()
.flatMap(m->m.keySet().stream())
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting())
.entrySet().stream()
.filter(es->es.getValue()>1)
.map(es->es.getKey())
.collect(Collectors.toList());
}
由于集合项是唯一的,因此不需要检查集合是否包含键。只需反复抛出所有关键点,将它们添加到集合中并使用结果。哇,谢谢。你能解释一下它是如何工作的吗,特别是“Collectors.toMap(Function.identity(),x->false,(a,b)->true)”?@villabilla是的,收集是一个技巧,在值部分,你只需使用true表示重复,false表示不重复。你能解释一下下面的部分(技术上)Collectors.toMap是如何工作的吗(Function.identity(),x->false,(a,b)->true)@panagiotisbugioukosx->false
表示如果存在唯一元素,则返回false;(a,b)->true
表示如果a和b相等,则表示存在重复项,因此返回true,以了解更多详细信息
[k0, k1, k3]
@SafeVarargs
private static Set<String> findDuplicateKeys(Map<String, ?>... maps) {
Set<String> keys = new HashSet<>();
return Arrays.stream(maps)
.flatMap(map -> map.keySet().stream())
.filter(key -> !keys.add(key))
.collect(Collectors.toSet());
}
private List<String> findDups(Map<String, ?>... maps) {
return Arrays.asList(maps).stream()
.flatMap(m->m.keySet().stream())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(es->es.getValue() > 1)
.map(es->es.getKey())
.collect(Collectors.toList());
}