Write a Java Program to Check if a queue contains a specific element


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and then check if the queue contains a specific element using the contains() method.

  • A Queue interface is implemented using the LinkedList class to create a queue to store integers.
  • Several integer elements (10, 23, 2, 18, 17) are added to the queue using the add() method.
  • The code defines a variable elecheck with the value 23. This is the element we want to check if it exists in the queue.
  • The contains() method is used to check if the specific element (elecheck) exists in the queue. It returns a boolean value (true or false) depending on whether the element is found or not.
  • The code then prints whether the queue contains the specified element or not, based on the boolean result from the contains() method.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueContainsElement
{
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
 
		// Adding elements to the queue
		queue.add(10);
		queue.add(23);
		queue.add(2);
		queue.add(18);
		queue.add(17);
 
		// Checking if the queue contains a specific element
		int elecheck = 23;
 
		boolean ele = queue.contains(elecheck);
 
		if(ele)
		{
			System.out.println("The Queue Contains " + elecheck);
		}
		else
		{
			System.out.println("The Queue Does Not Contain " + elecheck);
		}
    }
}

Output

The Queue Contains 23

Example Programs