What is the LinkedList.removeLastOccurrence method in Java?

A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is the doubly-linked listA kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package.

The removeLastOccurrence method

The removeLastOccurrence method can be used to remove the last occurrence of the specified element in the LinkedList.

Syntax

public boolean removeLastOccurrence(Object o);

Parameters

This method takes the element to be removed from the list as an argument.

Return value

This method returns true if the specified element is present in the specified element.

Code

The code below demonstrates how to use the removeLastOccurrence method:

import java.util.LinkedList;
class LinkedListRemoveLastOccurrenceExample {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("1");
System.out.println("The list is " + list);
System.out.println("Is element present " + list.removeLastOccurrence("1"));
System.out.println("The list is " + list);
}
}

Explanation

In the code above:

  • In line number 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line number 4, we created a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • From line number 5 to 7, we used the add method of the list object to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
  • On line number 10, we used the removeLastOccurrence method to remove the last occurrence of the element "1". The element "1" is present in two indexes, 0 and 2. After calling this method, the element at index 2 will be removed.
list.removeLastOccurrence("1"); // true
list; // ["1", "2"]

Free Resources