相关问题:
- 具有固定大小的 Java PriorityQueue
- 如何使用优先队列?
- 获取数组中 n 个最小元素的索引
- Scala:有没有办法像在 Java 中一样使用 PriorityQueue?
我有一个非常大的数据集(超过 500 万件商品)我需要得到N最大从中获取物品。最自然的方法是使用堆/优先级队列只存储前 N 个项目。 JVM (Scala/Java) 的优先级队列有几种很好的实现,即:
- scala.collection.mutable.PriorityQueue
- java.util.PriorityQueue
- lucene.util.PriorityQueue
前两个很好,但它们存储了所有项目,在我的例子中,这带来了严重的内存开销。第三种(Lucene 实现)没有这样的缺点,但正如我从文档中看到的,它也不支持自定义比较器,这使得它对我来说毫无用处。
所以,我的问题是:有没有PriorityQueue
执行 with 固定容量 and 定制比较器?
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;
}
}
}
}
(where NaturalComparator
取自this问题)
你怎么能说Lucene不支持自定义比较器呢?
它是抽象的,你必须实现抽象方法lessThan(T a, T b)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)