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:
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
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.