Search for a element LinkedList in Java

In this example we will learn how to search if a element is present in the LinkedList or not. We will use the contains(Object o) method of java.util.LinkedList class.

import java.util.LinkedList;

public class ClearMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList list1 = new LinkedList();
		
		// use add() method to add elements to the LinkedList
		list1.add("Element1");
		list1.add("Element2");
		list1.add("Element3");
		
		//Checking if Element2 is present or not		
		if(list1.contains("Element2"))
		{
			System.out.println("Element2 is present at the index "+list1.indexOf("Element2"));
		}
		else
		{
			System.out.println("Element2 is not present in the list");
		}
	}
}

Output

Element2 is present at the index 1

Leave a Reply

Your email address will not be published. Required fields are marked *