Removing doubles from a list
-2
The method 'removeDoubles' uses a HashSet to remove double elements from a list without creating another list. The first occurrences of the multiple elements are kept, others will be removed. The order of the list will be preserved. The parameter list's iterator must support remove. Example of use is given in the main-method.
import java.util.*;
class RemoveDoubles {
public static void main(String[] args) {
List<String> animals = new ArrayList<String>();
animals.add("Horse");
animals.add("Crocodile");
animals.add("Cat");
animals.add("Hamster");
animals.add("Cat");
animals.add("Cat");
animals.add("Crocodile");
animals.add("Mouse");
animals.add("Elk");
System.out.println(animals);
removeDoubles(animals);
System.out.println(animals);
}
public static <E, T extends List<E>> T removeDoubles(T list) {
Iterator<E> it = list.iterator();
Set<E> s = new HashSet<E>();
while (it.hasNext()) {
E elem = it.next();
if (!s.add(elem)) {
it.remove();
}
}
return list;
}
}






See the snippet
Regarding the comment "just use HashSet", HashSet would destroy the order.
Here's a very clean solution using LinkedHashSet.
public static void main(String[] args) {
List animals = new ArrayList();
animals.add("Horse");
animals.add("Crocodile");
animals.add("Cat");
animals.add("Hamster");
animals.add("Cat");
animals.add("Cat");
animals.add("Crocodile");
animals.add("Mouse");
animals.add("Elk");
System.out.println(animals);
animals = removeDoubles(animals);
System.out.println(animals);
}
public static List removeDoubles(T list) {
if (list == null)
return list;
return new ArrayList(new LinkedHashSet(list));
}
Note in your original example you were assuming the list that is passed to the removeDoubles method was being modified in the method, and you ignored the list being returned by the method. Those are some bad assumptions to make.