Java Utility Library

Java LinkedList - pollFirst() Method



The java.util.LinkedList.pollFirst() method is used to retrieve and remove the head (first element) of the list. Every removal of element results into reducing the list size by one unless the list is empty. The method returns null, if the list is empty.

Syntax

public E pollFirst()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the head (first element) of the list, or null if the list is empty.

Exception

NA.

Example:

In the example below, the java.util.LinkedList.pollFirst() method is used to retrieve and remove the head of 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(20);
    MyList.add(30);

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

    //deleting first element
    while(MyList.size() != 0) {
      System.out.println(MyList.pollFirst() + " is deleted from list.");
   }
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30]
10 is deleted from list.
20 is deleted from list.
30 is deleted from list.

❮ Java.util - LinkedList