How to create a reverse map when original map contains collection as the value?
You can break the Map
into key-value pairs (where each key and value is a single String
) by using flatMap
, and then collect them as you wish:
Map<String,Set<String>> rev =
original.entrySet ()
.stream ()
.flatMap (e -> e.getValue ()
.stream ()
.map (v -> new SimpleEntry<String,String>(v,e.getKey ())))
.collect(Collectors.groupingBy (Map.Entry::getKey,
Collectors.mapping (Map.Entry::getValue,
Collectors.toSet())));
System.out.println (rev);
Output:
{Apple=[Jack, Scott], Pear=[Scott], Orange=[Jack], Banana=[Jack, Scott]}
A more imperative but simpler solution would be using forEach
:
Map<String, Set<String>> original,result; // initialised
original.forEach((key, value) -> value.forEach(v ->
result.computeIfAbsent(v, k -> new HashSet<>()).add(key)));