Question

Let's take a map :

  • A -> {1, 2, 3}
  • B -> {3, 4, 5}
  • C -> {2, 3, 5}

I need to reverse this map and obtain :

  • 1 -> {A}
  • 2 -> {A, C}
  • 3 -> {A, B, C}
  • 4 -> {B}
  • 5 -> {B, C}

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?

Was it helpful?

Solution

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top