Tuesday, November 2, 2010

Remove Duplicate value from ArrayList

ArrayList arrayListSubin = new ArrayList();
  
 
arrayListSubin.add("A");
 
arrayListSubin.add("A");
 
arrayListSubin.add("B");
 
arrayListSubin.add("B");
 
arrayListSubin.add("B");
 
arrayListSubin.add("C");
  
  //Create a HashSet which allows no duplicates
  HashSet hashSet = new HashSet(
arrayListSubin);

  //Assign the HashSet to a new ArrayList
  ArrayList arrayList2 = new ArrayList(hashSet) ;
  
  //Ensure correct order, since HashSet doesn't
  Collections.sort(arrayList2);
  
  for (Object item : arrayList2)
    System.out.println(item);

Note that you will have to sort the ArrayList if you want to be sure that the items remain
in correct order by calling the sort method of the Collection class.

This will produce the following output:

A
B
C

1 comment:

  1. One of the impressive and interesting information about it,thanks for sharing and great effort.

    ReplyDelete