Search a particular element in a LinkedList in Java

Java 8Object Oriented ProgrammingProgramming

A particular element can be searched in a LinkedList using the method java.util.LinkedList.indexOf(). This method returns the index of the first occurance of the element that is searched. If the element is not available in the LinkedList, then this method returns -1.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("A");
      l.add("B");
      l.add("C");
      l.add("D");
      l.add("E");
      System.out.println("The index of element B in LinkedList is: " + l.indexOf("B"));
      System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));
   }
}

Output

The index of element B in LinkedList is: 1
The index of element Z in LinkedList is: -1

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. LinkedList.indexOf() returns the index of the first occurrence of “B” and “Z” and that is displayed. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("A");
l.add("B");
l.add("C");
l.add("D");
l.add("E");
System.out.println("The index of element B in LinkedList is: " + l.indexOf("B"));
System.out.println("The index of element Z in LinkedList is: " + l.indexOf("Z"));
raja
Published on 11-Jan-2019 06:59:38
Advertisements