Computer >> Computer tutorials >  >> Programming >> Java

How to remove the redundant elements from an ArrayList object in java?


The interface set does not allow duplicate elements. The add() method of this interface accepts elements and adds to the Set object, if the addition is successful it returns true if you try to add an existing element using this method, the addition operations fails to return false.

Therefore, to remove redundant elements of an ArrayList object −

  • Get/create the required ArrayList.

  • Create an empty set object.

  • Try to add all the elements of the ArrayList object to set objectives.

  • Clear the contents of the ArrayList using the clear() method.

  • Now, using the addAll() method add the contents of the set object to the ArrayList again.

Example

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class RemovingDuplicates {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFX");
      list.add("Java");
      list.add("JavaFX");
      list.add("OpenCV");
      list.add("Java");
      list.add("JOGL");
      list.add("JOGL");
      list.add("HBase");
      list.add("Flume");
      list.add("HBase");
      list.add("Impala");
      System.out.println("Contents of the Array List : \n"+list);
      //Retrieving Iterator object of the ArrayList class
      Iterator<String> it = list.iterator();
      //Creating an empty Set object
      Set<String> set = new HashSet<String>();
      //Adding elements of the ArrayList to the Set object
      while(it.hasNext()) {
         set.add(it.next());
      }
      //Removing all the elements from the ArrayList
      list.clear();
      //Adding elements of the set back to the list
      list.addAll(set);
      System.out.println("Contents of the Array List after removing duplicate elements: \n"+list);
   }
}

Output

Contents of the Array List :
[JavaFX, Java, JavaFX, OpenCV, Java, JOGL, JOGL, HBase, Flume, HBase, Impala]
Contents of the Array List after removing duplicate elements:
[JavaFX, Java, OpenCV, JOGL, Flume, Impala, HBase]