Signup/Sign In
PUBLISHED ON: JANUARY 29, 2021

How to Remove Duplicates from ArrayList

In this post, we are going to remove duplicate elements from ArrayList in Java. ArrayList is a class which is implementation class of List interface in collection framework and used to store data.

Since ArrayList allows us to store duplicate elements therefor sometimes we need to get unique elements from the ArrayList then we have to remove the duplicate elements.

To remove the duplicates there is a simple and easy way, just convert the ArrayList to HashSet and get the unique elements. Since HashSet stores unique elements only. It removes all the duplicates automatically.

So to remove duplicates we are using two approaches one is converting to HashSet and the second is to use a distinct() method of stream that returns unique elements from a stream. See the examples.

Time for an Example:

Let's create an example to remove all duplicates from the ArrayList. Here, we are using HashSet and passing Arraylist as n argument to its constructor. It returns a unique Set but we want an ArrayList, so convert it back to ArrayList by passing it to the ArrayList constructor.

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

public class Main {
	public static void main(String[] args){
		ArrayList<Integer> arrList1 = new ArrayList<>();
		arrList1.add(1030);
		arrList1.add(1020);
		arrList1.add(1010);
		arrList1.add(1030);
		System.out.println(arrList1);
		// Remove duplicates
		HashSet<Integer> set = new HashSet<Integer>(arrList1);
		// Convert back to ArrayList
		arrList1 = new ArrayList<Integer>(set); 
		System.out.println(arrList1);
		
	}
}


[1030, 1020, 1010, 1030]
[1010, 1030, 1020]

Example:

If you don't want to convert ArrayList to HashSet then you can use another approaoch Steam API. The stream provides a distinct() method that remove duplicates from stream and toList() method returns a list of unique elements.

import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args){
		ArrayList<Integer> arrList1 = new ArrayList<>();
		arrList1.add(1030);
		arrList1.add(1020);
		arrList1.add(1010);
		arrList1.add(1030);
		System.out.println(arrList1);
		// Remove duplicates
		arrList1 = (ArrayList<Integer>)arrList1.stream().distinct().collect(Collectors.toList()); 
		System.out.println(arrList1);
		
	}
}


[1030, 1020, 1010, 1030]
[1030, 1020, 1010]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.