Java Utility Library

Java LinkedList - lastIndexOf() Method



The java.util.LinkedList.lastIndexOf() method returns index of the last occurrence of the specified element in the list. It returns -1 if element is not present in the list.

Syntax

public int lastIndexOf(Object obj)

Parameters

obj Specify the element to search for in the list.

Return Value

Returns the index of the last occurrence of the specified element in the list, or -1 if element is not present in the list.

Exception

NA.

Example:

In the example below, the java.util.LinkedList.lastIndexOf() method is used to find the index of last occurrence of 15 in the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist
    MyList.add(10);
    MyList.add(15);
    MyList.add(30);
    MyList.add(15);
    MyList.add(40);

    System.out.print("15 appeared last time at index=" + MyList.lastIndexOf(15)); 
  }
}

The output of the above code will be:

15 appeared last time at index=3

❮ Java.util - LinkedList