Java Utility Library

Java LinkedList - removeFirstOccurrence() Method



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

Syntax

public boolean removeFirstOccurrence(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.removeFirstOccurrence() method is used to remove the first 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(15);

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

    //remove the first occurrence of 15
    MyList.removeFirstOccurrence(15);

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

The output of the above code will be:

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

❮ Java.util - LinkedList