Search code examples
javacollectionsguava

how to convert HashMultiset<String> to Map<String,Integer>


Is there some trick to convert HashMultiset<String> to Map<String,Integer>, except from iterating all the entries in the Set?
Update: The Integer should represent the count of String in the multiset.


Solution

  • Updated to java 8, here is what I found as the best answer (based on other answers):

    public static <E> Map<E, Integer> convert(Multiset<E> multiset) {
        return multiset.entrySet().stream().collect(
            Collectors.toMap(x->x.getElement(),x->x.getCount()));
    }
    

    or:

    public static <E> Map<E, Integer> convert(Multiset<E> multiset) {
        return multiset.entrySet().stream().collect(
            Collectors.toMap(Entry::getElement,Entry::getCount));
    }