Removing doubles from a list
0
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;
}
}





There are currently no comments for this snippet.