LinkedList lastIndexOf() Method in Java
In Java, the lastIndexOf() method of LinkedList is used to find the last occurrence of the specified element in the list. If the element is present it will return the last occurrence of the element, otherwise, it will return -1.
Syntax of LinkedList lastIndexOf() Method
public int lastIndexOf(Object o);
Return type:
- If the element is present then the index of the last occurrence of the element is returned
- If the element is not present it will return -1.
Example: Here, we use lastIndexOf() method to return the last occurrence of the specified element in the list.
// Java Program to demonstrate the
// use of lastIndexOf()
import java.util.LinkedList;
public class Geeks {
public static void main(String args[]) {
// Creating an empty LinkedList
LinkedList<Integer> l = new LinkedList<Integer>();
// Use add() to insert
// elements in the list
l.add(10);
l.add(20);
l.add(30);
l.add(40);
l.add(20);
l.add(40);
// Displaying the LinkedList
System.out.println("" + l);
// Use lastIndexOf() to return the last occurence of
// the specified element in the LinkedList
System.out.println(
"Last occurrence of 30 is at index: "
+ l.lastIndexOf(30));
System.out.println(
"Last occurrence of 40 is at index: "
+ l.lastIndexOf(40));
}
}
Output
[10, 20, 30, 40, 20, 40] Last occurrence of 30 is at index: 2 Last occurrence of 40 is at index: 5