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
PriorityQueueis not empty, it returns an element present at the head of thePriorityQueue. - If the
PriorityQueueis empty, it returns aNULLvalue.
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
Mainclass as Java is class-based and object-oriented and works solely with classes. -
Line 4: We make a
mainfunction that is the entry point of our Java program. -
Line 6: We declare a
PriorityQueuethat 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
PriorityQueueby using thePriorityQueue.add()method. -
Line 18: We display the head element of the
PriorityQueueusingPriorityQueue.peek()method.