Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava: construct a Multimap by inverting a Map

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.

like image 805
Fabian Zeindl Avatar asked Dec 21 '22 06:12

Fabian Zeindl


1 Answers

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()
    );
like image 121
Mark Peters Avatar answered Jan 05 '23 08:01

Mark Peters