Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a map

Tags:

java

guava

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?

like image 521
Arnaud Denoyelle Avatar asked Nov 01 '25 10:11

Arnaud Denoyelle


1 Answers

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

like image 187
Frank Pavageau Avatar answered Nov 03 '25 23:11

Frank Pavageau



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!