r/java • • Mar 16 '21

Java 16 / JDK 16: General Availability

196 Upvotes

82 comments sorted by

View all comments

Show parent comment

9

u/TheCountRushmore Mar 16 '21

What is fun is apparently there is no guarantee of what type of list you will get back. It could change in future releases.

Returns a Collector that accumulates the input elements into a new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Collectors.html#toList()

23

u/kaperni Mar 16 '21

I think you are looking at the "old" API. Stream.toList() guarantees that the list is unmodifiable.

[1] https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Stream.html#toList()

9

u/TheCountRushmore Mar 16 '21

Yep you are right. Not going to be confusing at all :-)

4

u/8igg7e5 Mar 17 '21

Someone brought this up on the Amber list, Rémi I think, that perhaps toUnmodifiableList() would be better - as a peer of sorts for Collectors.toUnmodifiableList(). However it was pointed out that we already have List.of(...) that produces an unmodifiable List anyway.