Write a Java program to Check whether an item exists in the LinkedList collection or not


The code demonstrates how to use the contains method of LinkedList in Java to check if an item exists in the list. In the Check_Exists class, a LinkedList object named col is created with a type parameter specified as String, indicating that it can only hold items of type String. Several color names, including "Pink", "Yellow", "Green", "Orange", "Red", and "Blue", are added to the col using the add method.

The System.out.println statement is used to print the color names in the col list. The contains method is then called on the col list with the argument "Orange", which is the item being checked for existence in the list. The result of the contains method is a boolean value, true if the item exists in the list, and false otherwise.

An if statement is used to check the result of col.contains("Orange"). If the result is true, meaning the item exists in the list, then the message "Item Exists" is printed using the System.out.println statement. Otherwise, if the result is false, meaning the item does not exist in the list, then the message "Item does Not Exist" is printed using the System.out.println statement.

Note that the contains method uses the equals method to compare the items in the list, so the items must implement the equals method properly for accurate comparison.

Source Code

import java.util.LinkedList;
public class Check_Exists
{
	public static void main(String[] args)
	{
		LinkedList <String> col = new LinkedList <String>();
		col.add("Pink");
		col.add("Yellow");
		col.add("Green");
		col.add("Orange");
		col.add("Red");
		col.add("Blue");
 
		System.out.println("Color Names : " + col);
 
		if (col.contains("Orange") == true)
		{			
			System.out.println("Item Exists");
		}
		else
		{
			System.out.println("Item does Not Exists");
		}
	}
}

Output

Color Names : [Pink, Yellow, Green, Orange, Red, Blue]
Item Exists

Example Programs