How to search an element inside a linked list in Java



Problem Description

How to search an element inside a linked list?

Solution

Following example demonstrates how to search an element inside a linked list using linkedlistname.indexof(element) to get the first position of the element and linkedlistname.Lastindexof(elementname) to get the last position of the element inside the linked list.

import java.util.LinkedList;

public class Main {
   public static void main(String[] args) {
      LinkedList<String> lList = new LinkedList<String>();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      lList.add("2");
      
      System.out.println("First index of 2 is:"+
      lList.indexOf("2"));
      
      System.out.println("Last index of 2 is:"+ 
      lList.lastIndexOf("2"));
   }
}

Result

The above code sample will produce the following result.

First index of 2 is: 1
Last index of 2 is: 5

The following is an another example to search an element inside a linked list.

import java.util.LinkedList;

public class Demo {
   public static void main(String args[]) {
      LinkedList<Integer> linkedlist1 = new LinkedList<>();
      linkedlist1.add(001);
      linkedlist1.add(002);
      linkedlist1.add(003);
      linkedlist1.add(004);
      linkedlist1.add(005);
      linkedlist1.add(003);
      System.out.println("First index of 004 is : " + linkedlist1.indexOf(004));
      System.out.println("Last index of 004 is : " + linkedlist1.lastIndexOf(004));
   }
}

Result

The above code sample will produce the following result.

First index of 004 is : 3
Last index of 004 is : 3
java_data_structure.htm
Advertisements