Program
import java.util.PriorityQueue; import java.util.Collections; import java.util.Iterator; public class PriorityQueueExample { public static void main(String[] args) { // TODO Auto-generated method stub PriorityQueue<String> queue= new PriorityQueue<String>(); queue.add("Amit"); queue.add("Vijay"); queue.add("Karan"); queue.add("Jai"); queue.add("Rahul"); //element() System.out.println("head:"+queue.element()); // peek() System.out.println("head:"+queue.peek()); System.out.println("iterating the queue elements:"); //iterator() Iterator itr=queue.iterator(); //hasNext() while(itr.hasNext()){ System.out.println(itr.next()); } //remove() queue.remove(); //poll() queue.poll(); System.out.println("after removing two elements:"); Iterator<String> itr2=queue.iterator(); //hasNext() while(itr2.hasNext()){ System.out.println(itr2.next()); } } }
Output
head:Amit iterating the queue elements: Amit Jai Karan Vijay Rahul after removing two elements: Karan Rahul Vijay
Description
public E element()
Retrieves, but does not remove, the head of this queue.
This method differs from peek only in that it throws an exception if this queue is empty.
This implementation returns the result of peek unless the queue is empty.
Specified by:
element in interface Queue<E>
Returns:
the head of this queue
Throws:
NoSuchElementException – if this queue is empty
Iterator iterator()
Returns an iterator over the elements in this collection.
There are no guarantees concerning the order in which the elements are returned
(unless this collection is an instance of some class that provides a guarantee).
Specified by:
iterator in interface Iterable<E>
Returns:
an Iterator over the elements in this collection
public E remove()
Retrieves and removes the head of this queue.
This method differs from poll only in that it throws an exception if this queue is empty.
This implementation returns the result of poll unless the queue is empty.
Specified by:
remove in interface Queue<E>
Returns:
the head of this queue
Throws:
NoSuchElementException – if this queue is empty
E peek()
Retrieves, but does not remove,
the head of this queue, or returns null if this queue is empty.
Returns:
the head of this queue, or null if this queue is empty
E poll()
Retrieves and removes the head of this queue,or returns null if this queue is empty.
Returns:
the head of this queue, or null if this queue is empty
boolean hasNext()
Returns true if the iteration has more elements.
(In other words, returns true if next() would return an element rather than throwing an exception.)
Returns:
true if the iteration has more elements
E next()
Returns the next element in the iteration.
Returns:
the next element in the iteration
Throws:
NoSuchElementException – if the iteration has no more elements