LinkedList removeFirstOccurrence() Method in Java
In Java, the removeFirstOccurrence() method of the LinkedList class is used to remove the first occurrence of the specified element from the list. If there is no occurrence of the specified element the list remains unchanged.
Example 1: Here, we use the removeFirstOccurence() method to remove the first occurrence of the specified element in a LinkedList of Strings.
// Use of removeFirstOccurrence() with Integers
import java.util.LinkedList;
public class Geeks {
public static void main(String[] args) {
// Creating an Empty LinkedList
LinkedList<String> l = new LinkedList<>();
// Use add() to add
// elements in the list
l.add("A");
l.add("B");
l.add("C");
l.add("B");
l.add("D");
// Displaying the original LinkedList
System.out.println("" + l);
// removeFirstOccurrence() is
// going to return true
System.out.println(
"First Occurence of B is removed: "
+ l.removeFirstOccurrence("B"));
// Here M is not present in the Linkedlist
// so removeFirstOccurrence() is going to return
// false
System.out.println(
"M is present in the Linked List: "
+ l.removeFirstOccurrence("M"));
// Displaying the new LinkedList
System.out.println("" + l);
}
}
Output
[A, B, C, B, D] First Occurence of B is removed: true M is present in the Linked List: false [A, C, B, D]
Syntax of LinkedList removeFirstOccurrence() Method
public boolean removeFirstOccurrence(Object o)
Return Type:
- This method is going to return true, if the element is found and removed from the list.
- This method is going to return false, if the element is not present in the list.
Example 2: Here, we use the removeFirstOccurence() method to remove the first occurrence of an integer element from the LinkedList.
// Use of removeFirstOccurrence() with Integers
import java.util.*;
public class Geeks {
public static void main(String args[]) {
// Creating an Empty LinkedList
LinkedList<Integer> l = new LinkedList<>();
// Use add() to add
// elements in the list
l.add(10);
l.add(20);
l.add(30);
l.add(20);
l.add(40);
// Displaying the original LinkedList
System.out.println("" + l);
// removeFirstOccurrence() is
// going to return true
System.out.println(
"First Occurence of 20 is removed: "
+ l.removeFirstOccurrence(20));
// Here 100 is not present in the Linkedlist
// so removeFirstOccurrence() is
// false
System.out.println(
"100 is present in the Linked List: "
+ l.removeFirstOccurrence(100));
// Displaying the new LinkedList
System.out.println("" + l);
}
}
Output
[10, 20, 30, 20, 40] First Occurence of 20 is removed: true 100 is present in the Linked List: false [10, 30, 20, 40]