Removing double entries from a List
9
This is a very convenient way to remove all doubles from a List in Java. The only prerequisite is that the elements in the list have proper equals and hashCode methods.
It work by using the constructor of a Set that takes a Collection as an argument.
I poured the snippet in a little program so can run it straight away.
It work by using the constructor of a Set that takes a Collection as an argument.
I poured the snippet in a little program so can run it straight away.
import java.util.*;
public class RemoveDoubles {
public static void main(String[] args) {
// illustrating that a set filters doubles
ArrayList list = new ArrayList();
list.add("a");
list.add("a");
list.add("c");
System.out.println("list.size(): " + list.size());
System.out.println("list: " + list);
HashSet set = new HashSet(list);
System.out.println("set.size(): " + set.size());
System.out.println("set: " + set);
list = new ArrayList(set);
System.out.println("list: " + list);
}
}
/*
list.size(): 3
list: [a, a, c]
set.size(): 2
set: [a, c]
list: [a, c]
*/






You can use a TreeSet if you want to have the objects in the resulting list in their natural order, but if you have to keep the order of the objects as they where in the original list the code from the snippet is useless.