Remove duplicate elements in Java with HashSet

Java 8Object Oriented ProgrammingProgramming

Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements.

Let us declare a list and add elements −

List < Integer > list1 = new ArrayList < Integer > ();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(400);
list1.add(500);
list1.add(600);
list1.add(600);
list1.add(700);
list1.add(400);
list1.add(500);

Now, use the HashSet implementation and convert the list to HashSet to remove duplicates −

HashSet<Integer>set = new HashSet<Integer>(list1);
List<Integer>list2 = new ArrayList<Integer>(set);

Above, the list2 will now have only unique elements.

Example

 Live Demo

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Demo {
   public static void main(String[] argv) {
      List<Integer>list1 = new ArrayList<Integer>();
      list1.add(100);
      list1.add(200);
      list1.add(300);
      list1.add(400);
      list1.add(400);
      list1.add(500);
      list1.add(600);
      list1.add(600);
      list1.add(700);
      list1.add(400);
      list1.add(500);
      HashSet<Integer>set = new HashSet<Integer>(list1);
      List<Integer>list2 = new ArrayList<Integer>(set);
      System.out.println("List after removing duplicate elements:");
      for (Object ob: list2)
         System.out.println(ob);
   }
}

Output

List after removing duplicate elements:
400
100
500
200
600
300
700
raja
Published on 25-Apr-2019 08:56:52
Advertisements