As the Java API says:
Java.util.PriorityQueue.PriorityQueue ()
Creates a with the PriorityQueue
default initial capacity (one) that orders their elements according to their natural ordering.
The default ordering of priority queue Priorityqueue is the natural order of the elements. Take advantage of this feature and use it as a small top pile to find the first k elements in the array.
Packagestructure;ImportJava.util.Iterator;ImportJava.util.PriorityQueue;ImportJava.util.Queue;/*** Priority Queue usage in Java *@authorDreamy **/ Public classPriorityqueuedemo {/** * @paramargs*/ Public Static voidMain (string[] args) {//Priorityqueue in Java is sorted by default in natural order int[] numbers = {4,5,2,1,9,6,8,7}; FINDTOPK (numbers); } //find the top K large in the array Private Static voidFINDTOPK (int[] numbers) {Queue<Integer> queue =NewPriorityqueue<integer>(); Final intK = 3; for(inti=0;i<k;i++) Queue.add (Numbers[i]); for(inti=k;i<numbers.length;i++){ intMin =Queue.peek (); if(numbers[i]>min) {Queue.poll (); Queue.offer (Numbers[i]); }} Iterator<Integer> ITR =Queue.iterator (); while(Itr.hasnext ()) {intnum =Itr.next (); SYSTEM.OUT.PRINTLN (num); } }}
Of course, Priorityqueue can also store custom objects, allowing element objects to implement comparable excuses, overriding CompareTo methods to implement custom sorting. Alternatively, you can also construct a priorityqueue, specifying a custom comparer comparator (as a parameter).
In addition Priorityqueue is non-thread-safe, if you want to consider the synchronization problem under multithreading, you can use the Priorityblockingqueue under the concurrent package.
Java Priority queue