Syntax error Remove duplicate elements in Java with HashSet

Remove duplicate elements in Java with HashSet



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
Updated on: 2019-07-30T22:30:25+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements