Google Collections Multiset是一组元素,每个元素都有一个计数(即可能多次出现)。
我不能告诉你我想做多少次以下
示例:前10个网址(按提及的#次),前10个标记(按#次应用),...
对于Google Collections Multiset,有哪些规范方法可以做到#2?
Here是关于它的博客文章,但该代码并不是我想要的。首先,它返回所有内容,而不仅仅是前N个。其次,它会复制(是否可以避免复制?)。第三,我通常想要一种确定性的排序,即如果计数相等则是抢七。其他尼特:它不是静态的等等。
答案 0 :(得分:4)
我用你要求的基本功能编写了方法,除了它们执行副本并缺乏确定性的打破平局逻辑。它们目前是谷歌内部的,但我们可能会在某些时候开源。这个番石榴issue有方法签名。
他们的算法类似于博客文章:排序条目列表。使用更好的selection algorithm会更快,但更复杂。
编辑:自Guava 11以来,这是implemented答案 1 :(得分:3)
为了给人们评论的另一个视角,我将发布我引用的博客文章的略微修改版本:
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;
}
}