This post will discuss how to remove the first element from a list in Java.

1. Using List.remove() method

A common solution is to remove the element at the specific position in the list is using the remove() method. It works by shifting any subsequent elements to the left. Note that UnsupportedOperationException will be thrown if the remove() method is called on an unmodifiable list.

Download  Run Code

Output:

[2, 3, 4, 5]

 
The remove() method throws an IndexOutOfBoundsException if the list is empty. To handle it, you can create a utility method with size check on the list.

Download  Run Code

Output:

[]

2. Using List.clear() method

Alternatively, you can get a view of the first element in the list which is backed by the original list, and call the clear() method on it. This can be done using the subList() method, as shown below.

Download  Run Code

Output:

[2, 3, 4, 5]

 
To avoid an exception when the list is empty, perform an additonal check for an empty list before getting the sublist.

Download  Run Code

Output:

[2, 3, 4, 5]

3. Using Deque.removeFirst() method

If you happen to use a Deque (ArrayDeque, LinkedList, etc.), removing the first element from it can be achieved in constant time. The idea is to use the removeFirst() method, which removes and returns the first element of the deque.

Download  Run Code

Output:

[2, 3, 4, 5]

 
The removeFirst() method throws an exception when the deque is empty. To be exception-safe, you can use the pollFirst() method instead, which returns null if the deque is empty.

Download  Run Code

Output:

[2, 3, 4, 5]

That’s all about removing the first element from a list in Java.