Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to convert a List to a Set in Java

What is the easiest way to convert a List to a Set in Java?

like image 573
OHHAI Avatar asked Sep 15 '09 22:09

OHHAI


People also ask

Can we convert List to Set in Java?

In this, we can convert the list items to set by using addAll() method. For this, we have to import the package java. util.

How do you convert a List into a Set?

We can convert the list into a set using the set() command, where we have to insert the list name between the parentheses that are needed to be converted. Hence, in the above case, we have to type the set(the_names) in order to convert the names, present in the list into a set.

Which method is used to convert the List in to Set?

The simplest way to convert list to set in Python is by using the set() function. The set() method is used to convert an iterable element such as a list, dictionary, or tuple into the set.

Can we convert List to HashSet in Java?

There are four ways to convert ArrayList to HashSet :Using constructor. Using add() method by iterating over each element and adding it into the HashSet. Using addAll() method that adds all the elements in one go into the HashSet. Using stream.


2 Answers

Set<Foo> foo = new HashSet<Foo>(myList); 
like image 120
sepp2k Avatar answered Sep 27 '22 18:09

sepp2k


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

like image 42
Spina Avatar answered Sep 27 '22 19:09

Spina