Guava: construct a Multimap by inverting a Map

╄→尐↘猪︶ㄣ 提交于 2019-12-24 06:27:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/8157080/guava-construct-a-multimap-by-inverting-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!