Merging a list of maps into a single map

Viewed 4602

I'm trying to merge a list of Map into a single one:

List<Map<String, List<Long>>> dataSet;
Map<String, Set<Long>> uniqueSets = dataset.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collector.of(
            HashSet<Long>::new,
            ...,
            ...
        )
    ));

The idea is that uniqueSet should hold a list of unique IDs (Longs) within each collection (identified by a String). But I'm not sure about the ... parts.

As for the requested example (in JSON):

Input:

[
    {
        "Collection1": [1, 2, 3, 3],
        "Collection2": [2, 3]
    },
    {
        "Collection1": [3, 4],
        "Collection3": [1, 2]
    }
]

Output:

{
    "Collection1": [1, 2, 3, 4],
    "Collection2": [2, 3],
    "Collection3": [1, 2]
}
5 Answers
Related