Let's take a map :
I need to reverse this map and obtain :
I achieved to do it with this code :
public static <U, V> Map<V, Set<U>> reverseMap(Map<U, Set<V>> map) {
Map<V, Set<U>> result = Maps.newHashMap();
for(Map.Entry<U, Set<V>> entry : map.entrySet()) {
for(V value : entry.getValue()) {
Set<U> set = result.get(value);
if(set == null) {
set = Sets.newHashSet();
result.put(value, set);
}
set.add(entry.getKey());
result.put(value, set);
}
}
return result;
}
But this is only a reverse indexing so I think that there might exist a predefined method somewhere to do this.
Do someone knows such a library? a method in Guava?
If you replace your HashMap<U, Set<V>>
by a HashMultimap<U, V>
(they're equivalent, and the Multimap
is easier to use), you can now use Multimaps.invertFrom()
which will populate a Multimap<V, U>
.
Note that as the Javadoc mentions, if you use an ImmutableMultimap
, you can then directly call ImmutableMultimap.inverse()
.