VOOZH about

URL: https://www.javacodegeeks.com/2021/04/java-16-stream-tolist.html

⇱ Java 16: Stream.toList() - Java Code Geeks


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.

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 Shariff
April 15th, 2021Last Updated: April 13th, 2021
1 365 1 minute read

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
St1mpy
5 years ago

This article is useless:

stream.collect(Collectors.toList());

The article does not mention when or why to use the toList method.

1
Reply
Back to top button
Close
wpDiscuz