Removing duplicate elements from a List

You can convert to a Set with:

Set<String> aSet = new HashSet<String>(list);

Or you can convert to a set and back to a list with:

list = new ArrayList<String>(new HashSet<String>(list));

Both of these, however, are not likely to preserve the order of the elements. To preserve order, you can use a HashSet as an auxiliary structure while iterating:

List<String> list2 = new ArrayList<String>();
HashSet<String> lookup = new HashSet<String>();
for (String item : list) {
    if (lookup.add(item)) {
        // Set.add returns false if item is already in the set
        list2.add(item);
    }
}
list = list2;

In the case of duplicates, only the first occurrence will appear in the result. If you want only the last occurrence to appear, that's a tougher problem. I'd tackle it by reversing the input list, applying the above, and then reversing the result.


This:

Set<String> set = new HashSet<String>();
set.addAll(list);
list.clear();
list.addAll(set);