How to Remove Elements From LinkedList Java

Java LinkedList Examples


This example shows how to remove elements from LinkedList in Java with an example.

Removing elements from a LinkedList

The example below shows:
  • How to remove the first element in the LinkedList.
  • How to remove the last element in the LinkedList.
  • How to remove the first occurrence of a given element in the LinkedList.
  • How to remove all the elements that satisfy a given predicate from the LinkedList.
  • How to clear the LinkedList completely.
package com.javaguides.collections.linkedlistexamples;

import java.util.LinkedList;

public class RemoveElementsFromLinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> fruitList = new LinkedList<>();

        fruitList.add("Apple");
        fruitList.add("banana");
        fruitList.add("mango");
        fruitList.add("Pinaple");

        System.out.println("Initial LinkedList = " + fruitList);

        // Remove the first element in the LinkedList
        String element = fruitList.removeFirst();  
        System.out.println("Removed the first element "
            + element + " => " + fruitList);

        // Remove the last element in the LinkedList
        element = fruitList.removeLast();   
        System.out.println("Removed the last element " 
          + element + " => " + fruitList);
        
        // Remove the first occurrence of the specified element from the LinkedList
        boolean isRemoved = fruitList.remove("banana");
        if(isRemoved) {
         System.out.println("Removed banana => " + fruitList);
        }
        
        // Removes all of the elements of this collection that 
        // satisfy the given predicate.
        fruitList.removeIf(programmingLanguage -> programmingLanguage.startsWith("C"));
        System.out.println("Removed elements starting with C => " + fruitList);
        
        //Removes all of the elements from this list. 
        // The list will be empty after this call returns.
        fruitList.clear();
        System.out.println("Cleared the LinkedList => " + fruitList);
    }
}
Output:
Initial LinkedList = [Apple, banana, mango, Pinaple]
Removed the first element Apple => [banana, mango, Pinaple]
Removed the last element Pinaple => [banana, mango]
Removed banana => [mango]
Removed elements starting with C => [mango]
Cleared the LinkedList => []

Comments