PriorityQueue in java

Queue Interface

To order the element, the Java Queue interface uses FIFO(First In First Out) method, i.e., the first element is removed first and the last element is removed at last.

Queue Interface declaration:

public interface Queue<E> extends Collection<E>

Queue Interface Methods:

Method Description
boolean add(object) It will insert the specified element into this queue and return true upon success.
boolean offer(object) It will insert the specified element into this queue.
Object remove() It will retrieve and eliminate the head of this queue.
Object poll() It will retrieve and eliminate the head of this queue, or return null if this queue is empty.
Object element() It will retrieve but do not eliminate the head of this queue.
Object peek() It will retrieve, but do not eliminate the head of the queue, or return null if the queue is empty.

PriorityQueue class:

In the facility of using a queue, without ordering the elements in a FIFO manner, the PriorityQueue class is used. The AbstractQueue class is inherited by it.

PriorityQueue class declaration:

Declaration for java.util.PriorityQueue class:

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue Example:

import java.util.*;  
public class PriorityQueueExample{  
public static void main(String args[]){  
PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("A");  
queue.add("B");  
queue.add("C");  
queue.add("D");  
queue.add("E");  
System.out.println("Head:"+queue.element());  
System.out.println("Head:"+queue.peek());  
System.out.println("Iterating the queue elements:");  
Iterator itr=queue.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
queue.remove();  
queue.poll();  
System.out.println("After removing two elements:");  
Iterator<String> itr2=queue.iterator();  
while(itr2.hasNext()){  
System.out.println(itr2.next());  
}  
}  
}

Output:

 

Please Share