我有一个地图集合
maps
,我想要一个包含地图中所有键的集合(并集),一个包含所有地图共有的所有键的集合(交集),以及一个包含所有键的集合仅在某些集合中,但不是全部(析取并)。
我的问题是:除了接受“相同”的恭维之外,还有没有办法获得析取并“diff”,即是否有任何方法可以在 for 循环中与“all”和“same”并行完成,而不是在创建这两个集合之后?其次,我必须获取地图集合的元素来初始化“相同”吗?或者可以用“retainAll”之外的其他函数构建在 for 循环中并初始化为空吗?
基本上,下面给出的方法的替代逻辑是什么(如果有)?
Set<String> same = new HashSet<>(maps.get(0).keySet());
Set<String> diff = new HashSet<>();
Set<String> all = new HashSet<>();
for(Map map : maps) {
all.addAll(map.keySet());
same.retainAll(map.keySet());
}
diff.addAll(all);
diff.removeAll(same);
如果优雅你的意思是基于流,也许尝试一下:
List<Map<String, String>> maps = new ArrayList<>();
// Fill maps and after:
Integer mapCount = maps.size();
Map<String, Integer> output = maps.stream().flatMap(m -> m.keySet().stream())
.collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + 1, TreeMap::new));
// Union
Collection<String> union = output.keySet();
// Intersection value = mapCount
Collection<String> intersection = output.entrySet().stream().filter(e -> mapCount.equals(e.getValue()))
.map(e -> e.getKey()).collect(Collectors.toList());
// Difference value != mapCount
Collection<String> different = output.entrySet().stream().filter(e -> !mapCount.equals(e.getValue()))
.map(e -> e.getKey()).collect(Collectors.toList());