这是一个返回一个条目的方法,按频率排序(更新:使用标志来切换升序/降序,并使用番石榴最喜欢的玩具:在有效的Java中找到,项目3):List
Enum Singleton Pattern
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;
}
测试代码:
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()));
}
输出:
升序:
一 (1)
二 (2)
三 (3)
四 (4)
降序:
四 (4)
三 (3)
二 (2)
一 (1)