org.bhu.nlp.utils.MaxHeap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of Baturu Show documentation
Show all versions of Baturu Show documentation
This is a IO library for NLP
package org.bhu.nlp.utils;
import java.util.*;
public class MaxHeap {
private PriorityQueue queue;
private int maxSize;
public MaxHeap(int maxSize, Comparator comparator) {
if (maxSize <= 0)
throw new IllegalArgumentException();
this.maxSize = maxSize;
this.queue = new PriorityQueue(maxSize, comparator);
}
public boolean add(E e) {
if (queue.size() < maxSize) {
queue.add(e);
return true;
} else {
E peek = queue.peek();
if (queue.comparator().compare(e, peek) > 0) {
queue.poll();
queue.add(e);
return true;
}
}
return false;
}
public MaxHeap addAll(Collection collection) {
for (E e : collection) {
add(e);
}
return this;
}
public List toList() {
ArrayList list = new ArrayList(queue.size());
while (!queue.isEmpty()) {
list.add(0, queue.poll());
}
return list;
}
}