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

Overview

The PriorityQueue.contains() method is used to check whether the specified element is present in the PriorityQueue or not. The PriorityQueue.contains() method is present in the PriorityQueue class inside the java.util package.

Syntax

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

public boolean contains(Object element);

Parameters

The PriorityQueue.contains() method accepts one parameter:

  • element: The element needs to be checked for its presence in the PriorityQueue.

Return Value

The PriorityQueue.contains() method returns a boolean value:

  • True: The boolean value returns True, if the element is present in the PriorityQueue.
  • False: The boolean value returns false, if the element is not present in the PriorityQueue.

Code

Let’s look at the code below:

import java.util.*;
class Main
{
public static void main(String[] args)
{
PriorityQueue<Integer> p = new PriorityQueue<Integer>();
p.add(2);
p.add(28);
p.add(6);
p.add(80);
p.add(28);
p.add(7);
p.add(15);
if(p.contains(7))
System.out.println("Element = 7 is present in the PriorityQueue.");
else
System.out.println("Element = 7 is not present in the PriorityQueue.");
if(p.contains(67))
System.out.println("Element = 67 is present in the PriorityQueue.");
else
System.out.println("Element = 67 is not present in the PriorityQueue.");
}
}

Explanation

  • Line 1: We import the required package.

  • Line 2: We make a Main class.

  • Line 4: We make a main() function.

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

  • Lines 8 to 14: We insert the elements in the PriorityQueue by using the PriorityQueue.add() method.

  • Lines 16 to 19: We check whether a specified element is present in the PriorityQueue or not and display the message accordingly.

  • Lines 21 to 24: We again check whether the specified element is present in the PriorityQueue or not and display the message accordingly.

So, this is how we can use the PriorityQueue.contains() method in Java.

Free Resources