英文:
Java collect Map of Sets
问题
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Set<Map<String, Set<String>>> mapsSet = new HashSet<>();
// Add your maps to the 'mapsSet' here
Map<String, Set<String>> combinedMap = mapsSet.stream()
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(set1, set2) -> {
Set<String> combinedSet = new HashSet<>(set1);
combinedSet.addAll(set2);
return combinedSet;
}
));
System.out.println(combinedMap);
}
}
请注意,上面的代码示例中,我已经省略了输入部分的处理,你需要将你的地图添加到 mapsSet
集合中。在运行代码时,它将按照你的要求,将所有地图合并成一个地图,并对相同键的值集进行联合。最终结果将打印在控制台上。
如果你还有其他问题,欢迎随时问我。
英文:
I have a set of maps
Set<Map<String, Set<String>>>
I would like, using java streams, to combine all the maps in the set into one where the keys are all the keys of the maps and the values the union of the sets which are associated to the same key.
Output:
Ma<String, Set<String>>
Example input:
[
{
a: [1,2,3],
b: [2,3,4]
},
{
a: [4,5,6]
}
]
Example output:
{
a: [1,2,3,4,5,6]
b: [2,3,4]
}
I tried some solution but so far not solved yet
答案1
得分: 2
你可以创建一个包含所有内部映射条目的流,并将它们收集到一个单独的映射中:
Map<String, Set<String>> output =
input.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> {v1.addAll(v2); return v1;}));
英文:
You can create a Stream of all the entries of all the inner maps, and collect them to a single map:
Map<String, Set<String>> output =
input.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(v1,v2) -> {v1.addAll(v2); return v1;}));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论