Sunday 29 July 2012

How to remove duplicate element from List ?


This example shows how to remove duplicate elements from a list object.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class CreateUniqueList {
 public static void main(String[] args) {

  /** Create a ArrayList object **/

  ArrayList< String > arrayList = new ArrayList< String >();

  /** Add elements to ArrayList.ArrayList occupies duplicate elements. **/

  arrayList.add("A");
  arrayList.add("B");
  arrayList.add("C");
  arrayList.add("D");
  arrayList.add("A");

  /**
   * HashSet(Collection c) - Constructs a new set containing the unique
   * elements in the specified collection. A set is a collection object
   * that cannot have a duplicate values, so by converting the list to a
   * set the duplicate value will be removed.
   **/

  Set set = new HashSet(arrayList);

  // Creating arrayList with the unique elements.

  arrayList = new ArrayList(set);

  System.out.println("The list contains..." + arrayList);

 }
}


The output is:

The list contains...[D, A, B, C]


No comments:

Post a Comment