A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/data_search.htm below:

How to search an element inside a linked list in Java

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4