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.

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
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
St1mpy
St1mpy
2 years ago

This article is useless:

stream.collect(Collectors.toList());

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

Back to top button