Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Set implementation in Collectors.toSet()? [duplicate]

I have the following code:

Stream.of(1, 4, 5).collect(Collectors.toSet());

From Javadoc of toSet() method one can read:

There are no guarantees on the type (...) of the Set returned

I took a look at the actual implementation of toSet() method and at a first sight it looks like HashSet is always returned (at least in JDK 11).

I know that implementation can change in the future without violation of the contract but is there currently any situation when different implementation than HashSet is returned?

like image 577
k13i Avatar asked Dec 11 '22 04:12

k13i


2 Answers

As of JDK 11, the type of Set returned by Collectors.toSet() is a HashSet. This can, of course, change in future versions of Java, and you should therefore not rely on this.

If you wish to use a specific type of Set, you should use Collectors.toCollection instead, and provide a lambda to create a collection of your choosing.

like image 142
Joe C Avatar answered Jan 06 '23 21:01

Joe C


Use Collectors.toCollection for different Set implementation:

// Accumulate names into a TreeSet
Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));
like image 33
user7294900 Avatar answered Jan 06 '23 21:01

user7294900