Easiest way to convert a List to a Set in Java Easiest way to convert a List to a Set in Java java java

Easiest way to convert a List to a Set in Java


Set<Foo> foo = new HashSet<Foo>(myList);


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).


If you use the Guava library:

Set<Foo> set = Sets.newHashSet(list);

or, better:

Set<Foo> set = ImmutableSet.copyOf(list);