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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With