Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you invert Map<v1, Set<v2>> to Map<v2, Set<v1>> in Java with stream()

I have a Map object Map<t1, Set<t2>>, and I want to go into the set and turn t2 in the sets into the keys of the new map. The original key t1 will be the new value of the map.
For example, given a map containing two entries

{key1: [a, b, c], key2: [c, d]}

The resulting map would be

{a: [key1], b: [key1], c: [key1, key2], d: [key2]}

[ ] denotes Set in the above examples.

like image 601
Zoff Avatar asked Dec 08 '22 16:12

Zoff


1 Answers

Java 8:

map.entrySet()
        .stream()
        .flatMap(e -> e.getValue()
                .stream()
                .map(v -> new SimpleEntry<>(v, e.getKey())))
        .collect(Collectors.groupingBy(Entry::getKey,
                Collectors.mapping(Entry::getValue, Collectors.toSet())))

Guava:

Multimaps.asMap(map.entrySet()
        .stream()
        .collect(ImmutableSetMultimap.flatteningToImmutableSetMultimap(
                Entry::getKey, e -> e.getValue().stream()))
        .inverse())

StreamEx:

EntryStream.of(map)
        .flatMapValues(Set::stream)
        .invert()
        .grouping(Collectors.toSet())
like image 60
shmosel Avatar answered Apr 15 '23 01:04

shmosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!