Write a Java Program to Remove duplicate elements from ArrayList

Removing duplicate elements from an ArrayList is a common task in Java programming.

Fortunately, it’s a simple and straightforward process.

In this tutorial, I’ll walk you through the steps to remove duplicate elements from an ArrayList.


First, let’s define what an ArrayList is.

An ArrayList is a resizable array implementation in Java that allows us to store and manipulate elements dynamically.

We can add, remove, and modify elements in an ArrayList at any point during runtime.

An ArrayList can contain duplicates, and our goal is to remove them.

To remove duplicate elements from an ArrayList, we’ll create a new ArrayList and add only the unique elements to it.

Here’s the code to accomplish that:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class RemoveDuplicates {
    public static void main(String[] args) {
        List<Integer> listWithDuplicates = new ArrayList<>();
        listWithDuplicates.add(1);
        listWithDuplicates.add(2);
        listWithDuplicates.add(3);
        listWithDuplicates.add(2);
        listWithDuplicates.add(4);
        listWithDuplicates.add(1);

        HashSet<Integer> setWithoutDuplicates = new HashSet<>(listWithDuplicates);
        List<Integer> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);

        System.out.println("Original List: " + listWithDuplicates);
        System.out.println("List without duplicates: " + listWithoutDuplicates);
    }
}

In the above code, we first create an ArrayList listWithDuplicates with some duplicate elements.

Next, we create a HashSet setWithoutDuplicates and pass the listWithDuplicates to its constructor.

A HashSet is a collection that does not allow duplicate elements.

When we pass our ArrayList to the HashSet constructor, it automatically removes the duplicates.

Finally, we create a new ArrayList listWithoutDuplicates and pass the setWithoutDuplicates to its constructor.

This creates a new ArrayList with only the unique elements.

We then print both the original ArrayList and the ArrayList without duplicates.

That’s it! With just a few lines of code, we’ve removed duplicate elements from an ArrayList.

Note that the order of the elements in the new ArrayList may not be the same as the original ArrayList.

If you need to maintain the order of the elements, you can use a LinkedHashMap instead of a HashSet.


In conclusion, removing duplicate elements from an ArrayList in Java is a simple and straightforward process.

We create a new HashSet from the ArrayList to remove duplicates, and then create a new ArrayList from the HashSet to get the unique elements.