Java Utility Library

Java PriorityQueue - contains() Method



The java.util.PriorityQueue.contains() method is used to check whether the queue contains the specified element or not. It returns true if the queue contains the specified element, else returns false.

Syntax

public boolean contains(Object obj)

Parameters

obj Specify element whose presence in the queue need to be tested.

Return Value

Returns true if the queue contains the specified element, else returns false.

Exception

NA

Example:

In the example below, the java.util.PriorityQueue.contains() method is used to check the presence of specified element in 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);

    //checking the presence of elements
    for(int i = 5; i <= 20; i += 5) {
      if(PQueue.contains(i))
        System.out.println(i +" is present in PQueue.");
      else
        System.out.println(i +" is NOT present in PQueue.");
    }       
  }
}

The output of the above code will be:

5 is NOT present in PQueue.
10 is present in PQueue.
15 is NOT present in PQueue.
20 is present in PQueue.

❮ Java.util - PriorityQueue