Write a Java program to Get the position of last occurrence of a given element in a LinkedList


The code demonstrates how to use the lastIndexOf() method in Java to find the position of the last occurrence of an element in a LinkedList. The LastOccurrence class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statement is used to print the initial state of the list linked list, which represents the elements in the list. The list.lastIndexOf("JAVA") method is called to find the position (index) of the last occurrence of the string "JAVA" in the list linked list. The returned index is printed using the System.out.println statement.

Note that the indexing in a LinkedList starts from 0, where the head element has an index of 0, the next element has an index of 1, and so on. If the element "JAVA" is not found in the list linked list, the lastIndexOf() method returns -1.

Source Code

import java.util.*;
public class LastOccurrence
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.add("CPP"); 
		list.add("PYTHON"); 
		list.add("RUBY"); 
		list.add("JAVA"); 
		list.add("PHP"); 
		list.add("C"); 
		list.add("MYSQL"); 
		System.out.println("LinkedList : "+list); 
		System.out.println("Get the Position of Last Occurrence in LinkedList : "+list.lastIndexOf("JAVA"));
	}
}

Output

LinkedList : [CPP, PYTHON, RUBY, JAVA, PHP, C, MYSQL]
Get the Position of Last Occurrence in LinkedList : 3

Example Programs