Core Java
Java 16: Stream.toList()
Java 16 introduces a handy new Stream.toList()
method which makes it easier to convert a stream into a list. The returned list is unmodifiable and calls to any mutator method will throw an UnsupportedOperationException
.
Here is some sample code:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | import java.util.stream.Stream; import static java.util.stream.Collectors.*; // Java 16 stream.toList(); // returns an unmodifiable list // Other ways to create Lists from Streams: stream.collect(toList()); stream.collect(toCollection(LinkedList:: new )); // if you need a specific type of list stream.collect(toUnmodifiableList()); // introduced in Java 10 stream.collect( collectingAndThen(toList(), Collections::unmodifiableList)); // pre-Java 10 |
Related post: Java 10: Collecting a Stream into an Unmodifiable Collection
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 16: Stream.toList() Opinions expressed by Java Code Geeks contributors are their own. |
This article is useless:
The article does not mention when or why to use the toList method.