Remove Duplicate Elements in ArrayList

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.


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 Reply

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