This post will discuss how to add an item at the beginning of a List in Java.

1. Using List.add() method

The standard solution to insert a specified item at the specified position in the list is to use the add(index, element) method in the List interface, which takes the index and the element to be inserted.

Download  Run Code

Output:

[Yellow, Red, Blue, Brown, Purple]

2. Using Deque.addFirst() method

The add() method takes O(n) time, since it shifts all the elements to the right to make place for a new element. Inserting an item at the beginning can be done in O(1) time if you happen to use a Deque (ArrayDeque, LinkedList, etc.). It offers the addFirst() method, which inserts the specified element at the front of the deque.

Download  Run Code

Output:

[Yellow, Red, Blue, Brown, Purple]

 
Note that the addFirst() method throws IllegalStateException if it fails to insert an element due to capacity restrictions. When using a capacity-restricted deque, using the offerFirst() method is generally preferable.

Download  Run Code

Output:

[Yellow, Red, Blue, Brown, Purple]

3. Using Collections.reverse() method

The idea here is to reverse the list, insert the specified element at its end, and reverse the list again to get the desired order. This solution works, but it is not recommended for production code.

Download  Run Code

Output:

[Yellow, Red, Blue, Brown, Purple]

That’s all about adding an item at the beginning of a List in Java.