Easiest way to convert a List to a Set in Java

2021-6-3 anglehua

What is the 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);

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


Powered by emlog 京ICP备15036472号-3 sitemap