Java – how to reverse a map

Let's look at a map:

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

I need to reverse this map and get:

>1 – > {one} > 2 – > {a, C} > 3 – > {a, B, C} > 4 – > {B} > 5 – > {B, C}

I did 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 just a reverse index, so I think there may be a predefined method to do this

Does anyone know such a library? Guava method?

Solution

If you replace HashMap < u, set < V > > with hashmultimap < u, V > (they are equivalent and Multimap is easier to use), you can now use multimaps Invertfrom() to populate the Multimap < V, u >

Note that, as mentioned in Javadoc, if you use immutable Multimap, you can call immutable Multimap directly inverse().

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>