In this tutorial, we will learn how to search elements in LinkedList in Java. We will be writing a java program that searches a given linked list for a specified element and returns its index as output.
Method of LinkedList class for searching element
There are two methods in linked list class that searches an element in the list.
public int indexOf(Object o)
: Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
public int lastIndexOf(Object o)
: Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
Java Program to search a given element in LinkedList
Let’s write the java program to use the above discussed methods to search an element.
import java.util.LinkedList; public class SearchInLinkedList { public static void main(String[] args) { // Step1: Create a LinkedList LinkedList<String> linkedlist = new LinkedList<String>(); // Step2: Add elements to LinkedList linkedlist.add("Tim"); linkedlist.add("Rock"); linkedlist.add("Hulk"); linkedlist.add("Rock"); linkedlist.add("James"); linkedlist.add("Rock"); //Searching first occurrence of element int firstIndex = linkedlist.indexOf("Rock"); System.out.println("First Occurrence: " + firstIndex); //Searching last occurrence of element int lastIndex = linkedlist.lastIndexOf("Rock"); System.out.println("Last Occurrence: " + lastIndex); } }
Output:
First Occurrence: 1
Last Occurrence: 5
Explanation:
The list contains several elements with the same string “Rock”, this is possible because a linked list can have duplicate elements. To find the first occurrence of element “Rock” in the linked list, we used the indexOf()
method and to find the last occurrence, we used lastIndexOf()
method.
Leave a Reply