4

why does Guava doesn't have the following factory call to create a MultiMap from a normal Map?

public static <K,V> MultiMap<K,V> invertMap(Map<V,K> map);

I have program-names mapped to an integer of how often they were called. I'd like to invert this, so that i can ultimately construct a TreeMap, sorted by call-count, which then are the keys leading to one or multiple program-names.

Fabian Zeindl
  • 5,860
  • 8
  • 54
  • 78

1 Answers1

11

How about:

public static <K,V> Multimap<K,V> invertMap(Map<V,K> map) {
    return Multimaps.invertFrom(Multimaps.forMap(map), ArrayListMultimap.create());
}

Doesn't seem like this requires a dedicated function. You can even get back to a TreeMap pretty easily:

Map<String, Integer> programCounts;
TreeMap<Integer, Collection<String>> map = 
    new TreeMap<>(
        Multimaps.invertFrom(
           Multimaps.forMap(programCounts),
           ArrayListMultimap.create()
        ).asMap()
    );
Mark Peters
  • 80,126
  • 17
  • 159
  • 190