Remove Duplicate Elements in ArrayList

It is a general and interesting code for beginners and this can be achieved in many ways in Java. This code, I would like to keep the code as simple as possible without using any methods and without using any laborious loops of C/C++. Here, I use only constructors but for adding elements to ArrayList like add().

Concepts to be known earlier

  1. ArrayList accepts duplicate elements.
  2. HashSet accepts only unique elements.
  3. TreeSet maintains sorted order.
These concepts are used in the following code Remove Duplicate Elements ArrayList.
import java.util.*;
public class NoDuplicates
{
  public static void main(String args[])
  {
    ArrayList al1 = new ArrayList();
    al1.add("Rose");        al1.add("Jasmine");  
    al1.add("Jasmine");     al1.add("Rose");

    HashSet hs1 = new HashSet(al1);    // HashSet keeps only unique elements by default
                                                       // if you would like array list back
    ArrayList al2 = new ArrayList(hs1);

    System.out.println("ArrayList with duplicates: " + al1);
    System.out.println("ArrayList without duplicates: " + al2);
                                                       // if you would like the array list elements in sorted order

    TreeSet s1 = new TreeSet(al1);     // TreeSet sorts the elements by default
    // System.out.println("SortedSet elements: " + s1);// you can print like this also
                                                       // if you would like array list back
    ArrayList al3 = new ArrayList(s1);
    System.out.println("ArrayList without duplicates and in sorted order: " + al3);
  }
}


Remove Duplicate Elements ArrayList
Output screen of Remove Duplicate Elements ArrayList

ArrayList elements al1 are added with duplicate elements of Rose and Jasmine. The ArrayList object al1 is passed to the constructor of HashSet hs1. HashSet nature eliminates the dulplicates automatically.

To place the ArrayList al1 elements with duplicates in sorted order, the al1 is passed to the constructor of TreeSet s1. TreeSet eliminates duplicates and also places the elements in sorted order implicitly.

To get the array list back from HashSet and TreeSet (if required), the ArrayList objects passed to their constructors as shown in the code.

Leave a Comment

Your email address will not be published.