Write a Java program to remove duplicates from ArrayList

29/04/2017 Amit Gupta 1586

In this article, we will learn how to remove duplicates from ArrayList. We know that we can add duplicate elements in ArrayList.

  • So to remove duplicate elements from ArrayList first we can copy all the elements of List into Set.
  • As we know we cannot add duplicate elements into Set. This will remove all the duplicates and only unique elements will remain in Set.
  • Now clear the original ArrayList using clear() method and copy the elements back to List.

Code Snippet

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

public class ListOperations {

	public static void main(String[] args) {
		
		//Input
		List lst = new ArrayList<>();
		lst.add(1);
		lst.add(1);
		lst.add(3);
		lst.add(5);
		System.out.println("List with Duplicate Elements");
		System.out.println(lst);
		
		//processing
		Set set = new HashSet(lst);
		
		lst.clear();
		
		lst.addAll(set);
		
		//output
		System.out.println("List with Unique Elements");
		System.out.println(lst);

	}
}

Output

List with Duplicate Elements
[1, 1, 3, 5]
List with Unique Elements
[1, 3, 5]

In this article, we learned how to remove duplicates from ArrayList.

Author
Author: Amit Gupta
Published On: 29/04/2017
Last revised On: 29/04/2017
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media