Java Utility Library

Java LinkedList - removeLastOccurrence() Method



The java.util.LinkedList.removeLastOccurrence() method is used to remove the last occurrence of the specified element from the list. If the list does not contain the element, it will be unchanged.

Syntax

public boolean removeLastOccurrence(Object obj)

Parameters

obj Specify the element to be removed from this list, if present.

Return Value

Returns true if the list contained the specified element.

Exception

NA.

Example:

In the example below, the java.util.LinkedList.removeLastOccurrence() method is used to remove the last occurrence of 15 from the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist
    MyList.add(10);
    MyList.add(15);
    MyList.add(30);
    MyList.add(15);
    MyList.add(40);

    //printing linkedlist
    System.out.println("MyList contains: " + MyList);

    //remove the last occurrence of 15
    MyList.removeLastOccurrence(15);

    //printing linkedlist
    System.out.println("MyList contains: " + MyList);
  }
}

The output of the above code will be:

MyList contains: [10, 15, 30, 15, 40]
MyList contains: [10, 15, 30, 40]

❮ Java.util - LinkedList