为了给人们提供另一个评论的角度,我将发布我引用的博客文章的略微修改版本:
package com.blueshiftlab.twitterstream.summarytools;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.Multiset.Entry;
public class Multisets {
// Don't construct one
private Multisets() {
}
public static <T> ImmutableList<Entry<T>> sortedByCount(Multiset<T> multiset) {
Ordering<Multiset.Entry<T>> countComp = new Ordering<Multiset.Entry<T>>() {
public int compare(Multiset.Entry<T> e1, Multiset.Entry<T> e2) {
return e2.getCount() - e1.getCount();
}
};
return countComp.immutableSortedCopy(multiset.entrySet());
}
public static <T> ImmutableList<Entry<T>> topByCount(Multiset<T> multiset,
int max) {
ImmutableList<Entry<T>> sortedByCount = sortedByCount(multiset);
if (sortedByCount.size() > max) {
sortedByCount = sortedByCount.subList(0, max);
}
return sortedByCount;
}
}