Write a Java program to Remove the last occurrence of a specified item from the LinkedList


The code demonstrates how to use the removeLastOccurrence method of LinkedList in Java to remove the last occurrence of a specified element from the list.

In the Main class, a LinkedList object named list is created without specifying any type parameter, allowing it to hold items of any type. Several items of different types, including an integer (23), a character ('T'), a double (53.89), a string ("Java"), a boolean (false), and two more strings (true and "Java") are added to the list using the add method.

The System.out.println statement is used to print the content of the list using the toString method, which will display the items in the order they were added to the list.

The removeLastOccurrence method is then called twice. The first call attempts to remove the last occurrence of the string "Java" from the list, and the second call attempts to remove the last occurrence of the integer 100. The return value of the method, which indicates whether the element was found and removed, is checked using an if statement. If the element is found and removed, a corresponding message is printed; otherwise, a different message is printed.

Finally, the System.out.println statement is used again to print the updated content of the list after the removal operation, using the toString method. Note that if the last occurrence of "Java" is found and removed, the updated list will no longer contain that element.

Source Code

import java.util.LinkedList;
public class Main
{
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.add(23);
		list.add('T');
		list.add(53.89);
		list.add("Java");
		list.add(false);
		list.add(true);
		list.add("Java");
		System.out.println("LinkedList : " + list);
 
		if (list.removeLastOccurrence("Java"))
		{			
			System.out.println("Last Occurrence of 'Java' is Removed");
		}
		else
		{			
			System.out.println("Last Occurrence of 'Java' is Not Removed");
		}
		if (list.removeLastOccurrence(100))
		{			
			System.out.println("Last Occurrence of '100' is Removed");
		}
		else
		{			
			System.out.println("Last Occurrence of '100' is Not Removed");
		}
 
		System.out.println("Updated LinkedList : " + list);
	}
}

Output

LinkedList : [23, T, 53.89, Java, false, true, Java]
Last Occurrence of 'Java' is Removed
Last Occurrence of '100' is Not Removed
Updated LinkedList : [23, T, 53.89, Java, false, true]

Example Programs