Convert multisets to map

I need to convert GuavaMultiset<String> to Map<String, Integer>(Key, Count).

I can not find any useful function for this. Is there anything less to this than my code below?

private static Map<String, Integer> multisetToMap(final Multiset<String> multiset) {
    Map<String, Integer> result = new HashMap<>();
    for(String element: multiset.elementSet()) {
        result.put(element, multiset.count(element));
    }
    return ImmutableMap.copyOf(result);
}
+3
source share
2 answers

Indeed, there is no Guava hidden function for this, and you are doing basically the right thing.

I did not notice a function request (open or another) for this. But if we ever implement this function request , you may have another alternative.

+1
source

Eclipse Collections ( GS Collections) Bag ( Multiset), toMapOfItemToCount().

HashBag<Integer> bag = HashBag.newBagWith(1, 2, 2, 3, 3, 3);
Map<Integer,Integer> map = bag.toMapOfItemToCount();
Assert.assertEquals(UnifiedMap.newWithKeysValues(1, 1, 2, 2, 3, 3), map);

UnifiedMap HashMap.

: Eclipse.

+2

All Articles