Thursday, October 23, 2025
HomeLanguagesJavaLinkedList lastIndexOf() Method in Java with Examples

LinkedList lastIndexOf() Method in Java with Examples

The lastIndexOf(Object element) method of LinkedList class present inside java.util package is used to check and find the occurrence of a particular element in the list. If the element is present in the list then the lastIndexOf() method returns the index of the last occurrence of the element otherwise it returns -1. This method is used to find the last occurrence of a particular element in LinkedList.

Syntax: 

LinkedList.lastIndexOf(Object element)

Parameters: The parameter element is of the type LinkedList. 

It refers to the element whose last occurrence is required to be checked.

Return Value: The position of the last occurrence of the element in the list otherwise if the element is not present in the list then the method returns -1. The returned value is of integer type.

Example:

Java




// Java Program to Illustrate lastIndexOf() Method
// of LinkedList class
  
// Importing required classes
import java.io.*;
import java.util.LinkedList;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Creating an empty LinkedList of string type
        LinkedList<String> list = new LinkedList<String>();
  
        // Adding elements in the list
        // using add() method
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");
  
        // Displaying the current elements inside LinkedList
        System.out.println("LinkedList:" + list);
  
        // The last position of an element is returned
        // using lastIndexOf() method and
        // displaying on the console
        System.out.println(
            "Last occurrence of Geeks is at index: "
            + list.lastIndexOf("Geeks"));
        System.out.println(
            "Last occurrence of 10 is at index: "
            + list.lastIndexOf("10"));
    }
}


Output: 

LinkedList:[Geeks, for, Geeks, 10, 20]
Last occurrence of Geeks is at index: 2
Last occurrence of 10 is at index: 3

 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS