how to convert HashMultiset<String> to Map<String,Integer>
You can use Maps.asMap. With lambda expression (Java 8) it will be a one-liner:
Maps.asMap(multiset.elementSet(), elem -> multiset.count(elem));
In Java 7 and below:
final Multiset<String> multiset = HashMultiset.create();
Map<String, Integer> freqMap = Maps.asMap(multiset.elementSet(),
new Function<String, Integer>() {
@Override
public Integer apply(String elem) {
return multiset.count(elem);
}
});
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));
}
With Eclipse Collections you can use the method toMapOfItemToCount
on a Bag
(aka Multiset), which will return a Map
with a key of the same type in the Bag
and an Integer
count.
Note: I am a committer for Eclipse collections.