Write a Java program to Remove Duplicates from ArrayList


This Java program demonstrates how to remove duplicates from an ArrayList using a Set. Here's how the code works:

  • An ArrayList named num of type Integer is created and several integers are added to it using the add() method.
  • The elements of the original ArrayList are displayed using the println() method.
  • A Set named primesWithoutDuplicates of type Integer is created using the LinkedHashSet class. The constructor of LinkedHashSet takes an ArrayList as its argument and creates a Set containing the same elements, but without duplicates.
  • The original ArrayList is cleared using the clear() method.
  • The elements of the Set are added back to the original ArrayList using the addAll() method.
  • The elements of the ArrayList without duplicates are displayed using the println() method.

Note that the LinkedHashSet class is used instead of the HashSet class to preserve the order of the elements in the original ArrayList. If the order of the elements is not important, the HashSet class can be used instead.

Source Code

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Remove_Duplicates
{
	public static void main(String args[])
	{
		List<Integer> num = new ArrayList<Integer>();
		num.add(23);
		num.add(3);
		num.add(65);
		num.add(17);
		num.add(7);
		num.add(23);
		num.add(3);
		num.add(11);
		System.out.println("list of prime numbers : " + num);
		Set<Integer> primesWithoutDuplicates
		= new LinkedHashSet<Integer>(num);
		num.clear();
		num.addAll(primesWithoutDuplicates);
 
		System.out.println("List of Numbers Without Duplicates : " + num);
	}
}

Output

list of prime numbers : [23, 3, 65, 17, 7, 23, 3, 11]
List of Numbers Without Duplicates : [23, 3, 65, 17, 7, 11]

Example Programs