Thursday, February 14, 2008

How to remove duplicate items from an ArrayList

This code example shows how to remove duplicate items from an ArrayList.
  ArrayList arrayList1 = new ArrayList();
    
  arrayList1.add("A");
  arrayList1.add("A");
  arrayList1.add("B");
  arrayList1.add("B");
  arrayList1.add("B");
  arrayList1.add("C");
    
  //Create a HashSet which allows no duplicates
  HashSet hashSet = new HashSet(arrayList1);

  //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
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory