【问题标题】:Find top N elements in a Multiset from Google Collections?从 Google Collections 中查找 Multiset 中的前 N ​​个元素?
【发布时间】:2011-03-03 00:44:38
【问题描述】:

Google CollectionsMultiset 是一组元素,每个元素都有一个计数(即可能出现多次)。

我无法告诉你我想要执行以下多少次

  1. 制作直方图(完全是多重集)
  2. 从直方图中按计数获取前 N 个元素

示例:前 10 个 URL(被提及 # 次)、前 10 个标签(被应用 # 次)、...

在给定 Google Collections Multiset 的情况下,执行 #2 的规范方法是什么?

Here 是一篇关于它的博客文章,但该代码并不是我想要的。首先,它返回所有内容,而不仅仅是前 N 个。其次,它复制(是否可以避免复制?)。第三,我通常想要一个确定性排序,即如果计数相等,则进行决胜局。其他 nits:它不是静态的,等等。

【问题讨论】:

    标签: java guava multiset


    【解决方案1】:

    我编写了具有您要求的基本功能的方法,除了它们执行复制并且缺乏确定性的平局逻辑。它们目前在 Google 内部,但我们可能会在某个时候将它们开源。这个 Guava issue 有方法签名。

    他们的算法类似于博客文章:对条目列表进行排序。使用更好的selection algorithm 会更快,但更复杂。

    编辑:从 Guava 11 开始,这是implemented

    【讨论】:

    • 怎么用它来获取top N元素?
    【解决方案2】:

    为了让人们评论的另一个角度,我将发布我引用的博客文章的略微修改版本:

    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;
        }
    }
    

    【讨论】:

    • 如果我理解正确,此解决方案将在您每次要检索前 N 个元素时复制和排序整个集合。我不确定您的要求是什么,但是堆排序解决方案在时间和空间上都胜过这个,所以我不确定有什么好处。
    • 您正在优化速度,我正在寻找我编写的最少代码行数。
    • 我明白了——这在你的帖子中并不清楚,尤其是你问到要避免复制。
    • 小心,您的比较器正在按计数降序排序
    • 好点。这是设计使然,但没有明确指出。 “top N”通常表示降序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2017-08-04
    • 2013-12-13
    • 2016-10-27
    相关资源
    最近更新 更多