I Spy Code - Blog

Get first and last index of a specified element in a LinkedList

Question:

How do you get the first and last index of a specified element in a LinkedList using java?

Answer:

Use the LinkedList indexOf() method. It returns the index of the first occurrence of the specified element in a LinkedList, or -1 if this list does not contain the element.

Use the LinkedList lastIndexOf() method. It returns the index of the last occurrence of the specified element in a LinkedList, or -1 if this list does not contain the element.

Here is a java example that shows how to get the first and last index of a specified element in a LinkedList:

Source: (example.go)

import java.util.LinkedList;
 
public class Example {
 
   public static void main(String[] args) {
 
      // Create  LinkedList
      LinkedList<String> list = new LinkedList<>();
 
      // Adding elements to the LinkedList
      list.add("Apple");
      list.add("Banana");
      list.add("Orange");
      list.add("Apple");
      list.add("Grape");
      list.add("Apple");
 
      // print out LinkedList
      System.out.println(list);
 
      // Get the first index of Apple
      int i = list.indexOf("Apple");
      System.out.println("First Index: " + i);
 
      // Get the last index of Apple
      i = list.lastIndexOf("Apple");
      System.out.println("Last Index: " + i);
   }
}
 

Output:

$ java Example
[Apple, Banana, Orange, Apple, Grape, Apple]
First Index: 0
Last Index: 5

References:

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#indexOf(java.lang.Object)
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#lastIndexOf(java.lang.Object)

Questions answered by this page:

Get the first occurrence of the specified element in a LinkedList
Get the first and last index of a specific element in a LinkedList