Thursday, 15 March 2012

Remove duplicates from an ArrayList

A way I have found of removing duplicates from a Collection is doing this is to put the list into a Set (which does not allow duplicates). If you really need the it to be a List then you can add the Set back to it:

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("test");
arrayList.add("test"); // fill the list..
// etc..
Set<String> set = new Set<String>(arrayList); // add to the set
arrayList.clear(); // clear the list
arrayList.addAll(set); // add the set back into the list without the duplicates

You can also use LinkedHashSet which preserves the order of the Collection:

Set<String> set = new LinkedHashSet<String>(arrayList);

No comments:

Post a Comment