What is the LinkedList.lastIndexOf method in Java?

The lastIndexOf method is used to get the index of the last occurrence of the specified element, in the LinkedList.

Linked list

A linked list is a collection of linear data elements. Each element or node contains data and reference parts. The data part has the value and the reference part has the address to the next element.

The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList class is the Doubly-linked list implementation of the List and Deque interfaces.

The LinkedList class is present in the java.util package.

Syntax

public int lastIndexOf(Object o);

Parameters

This method takes the element to be searched in the list as a parameter.

Return Value

This method returns the last index at which the specified element is present in the list. If the element is not present in the list, then -1 is returned.

Code

The code below demonstrates how to use the lastIndexOf method.

import java.util.LinkedList;
class LinkedListLastIndexOfExample {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("1");
System.out.println("The list is " + list);
System.out.println("Last Index of element '1' is : " + list.lastIndexOf("1"));
System.out.println("Last Index of element '2' is : " + list.lastIndexOf("2"));
System.out.println("Last Index of element '3' is : " + list.lastIndexOf("3"));
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line 4, we created a LinkedList objects with the name list.
LinkedList<String> list = new LinkedList<>();
  • From lines 5 to 7, we used the add method of the list object to add three elements("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("1");
  • In line 10, we used the lastIndexOf method of the list object to get the index of the last occurrence of the element "1". The element "1" is present in two indexes 0 and 2. We get 2 as result.
list.indexOf("1"); // 2
  • In line 11, we used the lastIndexOf method of the list object to get the index of the last occurrence of the element "2". The element "2" is only present at index 1, so it is returned.
list.indexOf("2"); // 1
  • In line 12, we used the lastIndexOf method of the list object to get the index of the last occurrence of the element "3". The element "3" is not present in the list, so -1 is returned.
list.indexOf("3"); // -1