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 16stream.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 liststream.collect(toUnmodifiableList()); // introduced in Java 10stream.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. |
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Thank you!
We will contact you soon.
👁 Photo of Fahd Shariff
Fahd ShariffApril 15th, 2021Last Updated: April 13th, 2021
Fahd ShariffApril 15th, 2021Last Updated: April 13th, 2021
1 365 1 minute read

This site uses Akismet to reduce spam. Learn how your comment data is processed.
This article is useless:
The article does not mention when or why to use the toList method.