相关问题:
- Java PriorityQueue with fixed size
- 如何使用PriorityQueue?
- 获取数组中N个最小元素的索引
- Scala:是否有一种像Java中那样使用PriorityQueue的方法?
我有一个非常大的数据集(超过500万个项目),我需要从中获取N个最大的项目。最自然的方法是使用堆/优先队列,仅存储前N个项目。JVM(Scala/Java)有几个很好的优先队列实现,即:
前两个很好,但它们存储所有项目,在我的情况下会产生关键的内存开销。第三个(Lucene实现)没有这样的缺点,但是从文档中可以看出,它也不支持自定义比较器,这使得它对我毫无用处。
所以,我的问题是:是否有一个具有固定容量和自定义比较器的PriorityQueue实现?
更新。最终,我基于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;
}
}
}
}
(其中
NaturalComparator
取自这个问题)请注意,此处的“自然比较器”是从上述问题中获取的。
elementsLeft == 0
,而在这种情况下它必须变为1。 - Inego