This post will discuss how to remove all elements from a List in Java.

1. Using clear() method

The standard solution to remove all elements from a list is using the clear() method, which efficiently makes the list empty. Note that it only works on mutable lists, and throws UnsupportedOperationException for unmodifiable list.

Download  Run Code

 
The following is the source code of the clear() method for the ‘ArrayList’ implementation of the List interface. It sets the array buffer into which the elements of the List are stored to null. For tree-based List implementations, it simply sets the root to null.

2. Using removeAll() method

An alternative idea is to call the removeAll() method, which removes all elements from a list that are present in the specified collection. This is demonstrated below:

Download  Run Code

 
This approach is not recommended as it will be extremely slow for a large collection.

3. Using remove() method

Starting with Java 8, we can get a stream of elements in the list and call the remove() method for each element.

This is demonstrated below. Note that we have used a copy of the list to avoid java.util.ConcurrentModificationException, as Java doesn’t allow concurrent modification on the List instance while iterating over it:

Download  Run Code

4. Using Iterator.remove() method

We can avoid creating a copy of the list by iterating over the list using a fail-safe iterator and calling the remove() method of the iterator. The iterator doesn’t throw ConcurrentModificationException when a thread modifies the list’s structure while another thread (or same thread) is iterating over it.

Download  Run Code

That’s all about removing all elements from a List in Java.