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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With