How to Remove Duplicate Elements from ArrayList in Java

In this tutorial you will learn how to remove duplicate elements from arraylist in Java.

We can remove repeated elements in arraylist by two ways.

  • Using HashSet – Do not maintain the insertion order.
  • Using LinkedHashSet – Maintain the insertion order.

 

First we create an ArrayList and add some duplicate elements to it.

Now copy elements of ArrayList to HashSet or LinkedHashSet.

Remove all elements of ArrayList by clear() method.

Finally copy elements of HashSet or LinkedHashSet back to the ArrayList.

Below example shows how to implement this.

 

How to Remove Duplicate Elements from ArrayList in Java

package com;

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

public class RemoveDuplicateElements {
	public static void main(String args[]){
		ArrayList<String> al1=new ArrayList<String>();
		ArrayList<String> al2=new ArrayList<String>();
		HashSet<String> hs=new HashSet<String>();
		LinkedHashSet<String> lhs=new LinkedHashSet<String>();
		
		al1.add("C");
		al1.add("C++");
		al1.add("C++");
		al1.add("Android");		
		al1.add("Java");
		al1.add("Java");
		
		al2.addAll(al1);
		
		System.out.println("HashSet");
		System.out.println("Before: "+al1);
		
		hs.addAll(al1);
		al1.clear();
		al1.addAll(hs);
		System.out.println("After: "+al1);

		System.out.println("\nLinkedHashSet");
		System.out.println("Before: "+al2);

		lhs.addAll(al2);
		al2.clear();
		al2.addAll(lhs);
		System.out.println("After: "+al2);
	}
}

 

Output

How to Remove Duplicate Elements from ArrayList in Java

You can observe the output. In case of HashSet, the insertion order is not maintained while in LinkedHashSet the insertion order is maintained.

Comment below if have any doubts regarding above tutorial.

1 thought on “How to Remove Duplicate Elements from ArrayList in Java”

Leave a Comment

Your email address will not be published. Required fields are marked *