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

标签 java scala heap priority-queue

相关问题:

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

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

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

UPD。最后我根据彼得的回答创建了自己的实现:

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

(其中NaturalComparator取自this问题)

最佳答案

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

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

关于java - 是否有具有固定容量和自定义比较器的 PriorityQueue 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7878026/

相关文章:

java - hibernate/JPA : How to find sub entities using InheritanceType. 已加入

java - 如何对使用该程序的人隐藏 MySQL 数据库的密码

Scala:用双引号 ("") 与单引号 ('' ) 分开

scala - Scala 的 Map.unzip 返回的原因 (Iterable, Iterable)

java - 空指针运行时异常

java - 膨胀 View

java - getIntent() 在第一个主要 Activity 中返回什么?

unit-testing - 对 Scala 词法分析器进行单元测试

python - heapify 和 heappush 有什么区别?哪个更好?

python - 如何使用对象比较函数反转 heapq 堆中元素的顺序?