What is the PriorityQueue.peek() method in Java?

Overview

In this shot, we’ll learn how to use the PriorityQueue.peek() method in Java.

Introduction

The PriorityQueue.peek() method is present in the PriorityQueue class inside the java.util package.

The PriorityQueue.peek() method is used to obtain the head element from the PriorityQueue.

Syntax

The syntax of the PriorityQueue.peek() function is given below:

public E peek();

Parameter

The PriorityQueue.peek() method does not accept any parameters.

Return value

The return value of the PriorityQueue.peek()method depends on the following conditions:

  • If the PriorityQueue is not empty, it returns an element present at the head of the PriorityQueue.
  • If the PriorityQueue is empty, it returns a NULL value.

Code

Let’s look at the code below:

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
System.out.println("Head Element of the priority queue is: " + pq.peek());
pq.add(2);
pq.add(28);
pq.add(6);
pq.add(80);
pq.add(28);
pq.add(7);
pq.add(15);
System.out.println("Head Element of the PriorityQueue is " + pq.peek());
}
}

Explanation

  • Line 1: We imported the required package.

  • Line 2: We have a Main class as Java is class-based and object-oriented and works solely with classes.

  • Line 4: We make a main function that is the entry point of our Java program.

  • Line 6: We declare a PriorityQueue that consists of Integer type elements.

  • Line 8: We print the current head element of the priority queue. Here, the output comes to null.

  • Lines 10–16: We insert the elements in the PriorityQueue by using the PriorityQueue.add() method.

  • Line 18: We display the head element of the PriorityQueue using PriorityQueue.peek() method.

Free Resources