Easiest way to convert a List to a Set? - In Java
I agree with sepp2k, but there are some other details that might matter:
new HashSet<Foo>(myList);
will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)
An alternative that gives a sorted set is:
new TreeSet<Foo>(myList);
This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).
All these answers are correct. Please remember, however, that these methods will silently eat all dups in the source list and since it uses .equals() you could end up losing objects that are equal but not identical (unless you don't implement .equals()). Of course, that's probably what you wanted or you wouldn't be using Set :).