Java Utility Library

Java PriorityQueue - peek() Method



The java.util.PriorityQueue.peek() method is used to retrieve, but does not remove, the head of this queue, or returns null if this queue is empty.

Syntax

public E peek()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the head of this queue, or null if this queue is empty.

Exception

NA.

Example:

In the example below, the java.util.PriorityQueue.peek() method is used to display the content of the given queue.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a priority queue
    PriorityQueue<Integer> PQueue = new PriorityQueue<Integer>();

    //populating the priority queue
    PQueue.add(10);
    PQueue.add(20);
    PQueue.add(30);
    PQueue.add(40);
    PQueue.add(50);

    //printing the priority queue
    System.out.println("PQueue contains: ");
    while(PQueue.size() != 0) {
      System.out.println(PQueue.peek());
      PQueue.remove();
   }
  }
}

The output of the above code will be:

PQueue contains: 
10
20
30
40
50

❮ Java.util - PriorityQueue