是否有具有固定容量和自定义比较器的PriorityQueue实现?

ffr*_*end 43 java heap scala priority-queue

相关问题:

我有一个非常大的数据集(超过500万件),我需要从中获得N个最大的项目.最自然的方法是使用堆/优先级队列,只存储前N个项目.JVM(Scala/Java)的优先级队列有几个很好的实现,即:

前2个很好,但它们存储了所有项目,在我的情况下会产生关键的内存开销.第三个(Lucene实现)没有这样的缺点,但正如我从文档中看到的那样,它也不支持自定义比较器,这对我来说没用.

所以,我的问题是:是否有PriorityQueue实现固定容量自定义比较

UPD.最后,根据Peter的回答,我创建了自己的实现:

public class FixedSizePriorityQueue<E> extends TreeSet<E> {

    private int elementsLeft;

    public FixedSizePriorityQueue(int maxSize) {
        super(new NaturalComparator());
        this.elementsLeft = maxSize;
    }

    public FixedSizePriorityQueue(int maxSize, Comparator<E> comparator) {
        super(comparator);
        this.elementsLeft = maxSize;
    }


    /**
     * @return true if element was added, false otherwise
     * */
    @Override
    public boolean add(E e) {
        if (elementsLeft == 0 && size() == 0) {
            // max size was initiated to zero => just return false
            return false;
        } else if (elementsLeft > 0) {
            // queue isn't full => add element and decrement elementsLeft
            boolean added = super.add(e);
            if (added) {
                elementsLeft--;
            }
            return added;
        } else {
            // there is already 1 or more elements => compare to the least
            int compared = super.comparator().compare(e, this.first());
            if (compared == 1) {
                // new element is larger than the least in queue => pull the least and add new one to queue
                pollFirst();
                super.add(e);
                return true;
            } else {
                // new element is less than the least in queue => return false
                return false;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(NaturalComparator这个问题中取出)

Rob*_*uir 17

你怎么能说Lucene不支持自定义比较器?

它的摘要你必须实现抽象方法 lessThan(T a, T b)


Ter*_*nal 14

虽然是一个老问题,但它可能对其他人有帮助.您可以使用Google Java库番石榴的minMaxPriorityQueue.

  • @Kranach的恒定因子将比正常的“ PriorityQueue”严重得多。使用普通的“ PriorityQueue”会做的更好,或者更好,“ Ordering.greatestOf”使用O(n)时间,O(k)内存算法。(我们正考虑弃用`MinMaxPriorityQueue`,只是因为它倾向于以这种方式被滥用。) (2认同)

Pet*_*rey 13

您可以使用SortedSet,例如TreeSet和自定义比较器,并在大小达到N时删除最小值.