LinkedList lastIndexOf() method in Java

The Java.util.LinkedList.lastIndexOf(Object element) method 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 last occurrence of the element otherwise it returns -1. This method is used to find the last occurrence of a particular element in a LinkedList.

Syntax:

LinkedList.lastIndexOf(Object element)

Parameters: The parameter element is of type LinkedList. It refers to the element whose last occurrence is required to be checked.

Return Value: The method returns 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.

Below program illustrate the Java.util.LinkedList.lastIndexOf() method:

filter_none

editclose

play_arrow

linkbrightness_4code

// Java code to illustrate lastIndexOf()

importjava.io.*;

importjava.util.LinkedList;

publicclassLinkedListDemo {

publicstaticvoidmain(String args[]) {

// Creating an empty LinkedList

LinkedList<String> list = newLinkedList<String>();

// Use add() method to add elements in the list

list.add("Geeks");

list.add("for");

list.add("Geeks");

list.add("10");

list.add("20");

// Dispalying the list

System.out.println("LinkedList:"+ list);

// The last position of an element is returned

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"));

}

}

chevron_right

filter_none

Output:

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

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.