Here's a method that returns a List
of entries, sorted by frequency (UPDATE: used a flag to toggle ascending / descending order and used Guava's favorite toy: the Enum Singleton Pattern
, as found in Effective Java, Item 3 ):
private enum EntryComp implements Comparator<Multiset.Entry<?>>{
DESCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(b.getCount(), a.getCount());
}
},
ASCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(a.getCount(), b.getCount());
}
},
}
public static <E> List<Entry<E>> getEntriesSortedByFrequency(
final Multiset<E> ms, final boolean ascending){
final List<Entry<E>> entryList = Lists.newArrayList(ms.entrySet());
Collections.sort(entryList, ascending
? EntryComp.ASCENDING
: EntryComp.DESCENDING);
return entryList;
}
Test code:
final Multiset<String> ms =
HashMultiset.create(Arrays.asList(
"One",
"Two", "Two",
"Three", "Three", "Three",
"Four", "Four", "Four", "Four"
));
System.out.println("ascending:");
for(final Entry<String> entry : getEntriesSortedByFrequency(ms, true)){
System.out.println(MessageFormat.format("{0} ({1})",
entry.getElement(), entry.getCount()));
}
System.out.println("descending:");
for(final Entry<String> entry : getEntriesSortedByFrequency(ms, false)){
System.out.println(MessageFormat.format("{0} ({1})",
entry.getElement(), entry.getCount()));
}
Output:
ascending:
One (1)
Two (2)
Three (3)
Four (4)
descending:
Four (4)
Three (3)
Two (2)
One (1)