Java LinkedList removeLastOccurrence(Object o) Method Example

In our previous article we have learnt about removeFirstOccurrence(Object o) removes the first occurrence of the specified element in this list, when traversing the list from head to tail. Now we will look into something which does the reverse of it removeLastOccurrence(Object o) method will remove last occurrence of the specified element in this list, when traversing the list from head to tail

Signature

public boolean removeLastOccurrence(Object o)

This method removes the last occurrence of the specified element of the list and returns true if the removal was successful.

Example

The following example shows the usage of java.util.LinkedList.removeLastOccurrence(o) method.

import java.util.LinkedList;

public class RemoveLastOccurenceLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		l.add("Element1");
		l.add("Element4");
		l.add("Element1");
		l.add("Element5");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list before remove**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing the last occurence of "Element1" from the list
		boolean flag = l.removeLastOccurrence("Element1");
		System.out.println("Is the removal successful ?? "+flag);
		
		//Printing the elements of the list
		System.out.println("**Elements of the list after remove**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list before remove**
Element1
Element2
Element3
Element1
Element4
Element1
Element5
Is the removal successful ?? true
**Elements of the list after remove**
Element1
Element2
Element3
Element1
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *