Remove duplicate items from an ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

Duplicate items can be removed from the ArrayList by using a HashSet as duplicate items are not allowed in a HashSet. So the ArrayList is converted into a HashSet and that removes the duplicate items. Then the HashSet is converted back into an ArrayList.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<String> aList1 = new ArrayList<String>();
      aList1.add("Adam");
      aList1.add("John");
      aList1.add("Mary");
      aList1.add("Adam");
      aList1.add("Mary");
      System.out.println("The ArrayList items are:" );
      for (String i : aList1)
      System.out.println(i);
      HashSet h = new HashSet(aList1);
      List aList2 = new ArrayList(h);
      System.out.println("\nThe ArrayList items after removing duplicates are:" );
      for (String i : aList2)
      System.out.println(i);
   }
}

Output

The output of the above program is as follows

The ArrayList items are:
Adam
John
Mary
Adam
Mary
The ArrayList items after removing duplicates are:
Adam
John
Mary

Now let us understand the above program.

The ArrayList aList1 is created. Then ArrayList.add() is used to add the elements to this ArrayList. Then the ArrayList elements are displayed. A code snippet which demonstrates this is as follows

List<String> aList1 = new ArrayList<String>();
aList1.add("Adam");
aList1.add("John");
aList1.add("Mary");
aList1.add("Adam");
aList1.add("Mary");
System.out.println("The ArrayList items are:" );
for (String i : aList1)
System.out.println(i);

After this, the ArrayList is converted into a HashSet and that removes the duplicate items. Then the HashSet is converted back into an ArrayList i.e. aList2. Then the ArrayList elements without duplicates are displayed. A code snippet which demonstrates this is as follows

HashSet h = new HashSet(aList1);
List aList2 = new ArrayList(h);
System.out.println("\nThe ArrayList items after removing duplicates are:" );
for (String i : aList2)
System.out.println(i);
raja
Published on 17-Jan-2019 17:46:06
Advertisements