What is the LinkedList.removeFirstOccurrence method in Java?
LinkedList
A LinkedList is a collection of linear data elements. Each element, or node, contains a data part and a reference part.
The data part has the value and the reference part has the address to the next element.
The elements are not indexed, so random access is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis the doubly-linked list implementation of theListandDequeinterfaces.
The LinkedList class is present in the java.util package.
What is the removeFirstOccurrence method of the LinkedList class?
The removeFirstOccurrence method is used to remove the first occurrence of the specified element in the LinkedList.
Syntax
public boolean removeFirstOccurrence(Object o);
Parameter
This method takes the element to be removed from the list as a parameter.
Return value
This method returns true if the list contains the specified element. Otherwise, it returns false.
Code
The code below demonstrates how to use the removeFirstOccurrence method.
import java.util.LinkedList;class LinkedListRemoveFirstOccurrenceExample {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.removeFirstOccurrence("1"));System.out.println("The list is " + list);}}
Explanation
In the above code:
- In line number 1, we import the
LinkedListclass.
import java.util.LinkedList;
- In line number 4, we create a
LinkedListobjects with the namelist.
LinkedList<String> list = new LinkedList<>();
- From line number 5 to 7, we use the
addmethod of thelistobject to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
- In line number 10, we use the
removeFirstOccurrencemethod to remove the first occurrence of the element"1". The element"1"is present in two indexes,0and2. After calling this method, the element at index0will be removed.
list.removeFirstOccurrence("1"); // true