public class Largest {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue(1);
queue.add(123);
queue.add(20);
queue.add(54);
queue.add(9);
queue.add(87);
queue.add(200);
queue.add(122);
queue.add(43);
queue.add(90);
queue.add(12);
queue.add(66);
queue.add(118);
queue.add(134);
queue.add(7);
queue.add(199);
queue.add(5);
queue.add(240);
int position = queue.size() - 10;
while(queue.size()>position) {
System.out.println("Remove...");
queue.poll(); // Remove head element
}
System.out.println("10th Highest :" + queue.poll());
}
}
To provide customized sorting, provide comparator implementation in PriorityQueue constructor.
class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
if(((Integer) o1).compareTo((Integer) o2) > 0) {
return -1;
} else if (((Integer) o1).compareTo((Integer) o2) < 0) {
return 1;
}
return 0;
}
}
And, use PriorityQueue constructor with initial capacity and customized Comparator object.
PriorityQueue queue = new PriorityQueue(1, new MyComparator());
No comments:
Post a Comment
Note: only a member of this blog may post a comment.