Java LinkedList removeFirst()

In this guide, you will learn about the LinkedList removeFirst() method in Java programming and how to use it with an example.

1. LinkedList removeFirst() Method Overview


The removeFirst() method of the LinkedList class in Java is used to remove and return the first element from this list. This method is part of the java.util.LinkedList class, which is a member of the Java Collections Framework.


public E removeFirst()


This method does not take any parameters.

Key Points:

- The removeFirst() method removes the first element from the LinkedList.

- It returns the element that was removed from the list.

- This method throws NoSuchElementException if the list is empty.

- It is equivalent to pollFirst(), except that removeFirst() throws an exception if the list is empty, whereas pollFirst() returns null.

2. LinkedList removeFirst() Method Example

import java.util.LinkedList;

public class LinkedListRemoveFirstExample {

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

        // Adding elements to the LinkedList
        linkedList.add("Element 1");
        linkedList.add("Element 2");
        linkedList.add("Element 3");

        // Printing the original LinkedList
        System.out.println("Original LinkedList: " + linkedList);

        // Using removeFirst() to remove the first element from the LinkedList
        String removedElement = linkedList.removeFirst();
        System.out.println("Removed Element: " + removedElement);
        System.out.println("LinkedList after removeFirst(): " + linkedList);


Original LinkedList: [Element 1, Element 2, Element 3]
Removed Element: Element 1
LinkedList after removeFirst(): [Element 2, Element 3]


In this example, a LinkedList is created and populated with some elements. 

The removeFirst() method is then used to remove the first element from the LinkedList. 

The output demonstrates the LinkedList at its initial state, the element that was removed, and the LinkedList after calling removeFirst(), verifying that the first element has been removed from the list.