Home » Java » Core Java » Java 10: Collecting a Stream into an Unmodifiable Collection

About Fahd Shariff

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.

Java 10: Collecting a Stream into an Unmodifiable Collection

Java 10 introduces several new methods to facilitate the creation of unmodifiable collections.

The List.copyOf, Set.copyOf, and Map.copyOf methods create new collection instances from existing instances. For example:

List<String> modifiable = Arrays.asList("foo", "bar");
List<String> unmodifiableCopy = List.copyOf(list);

// Note that since Java 9, you can also use "of" to create
// unmodifiable collections
List<String> unmodifiable = List.of("foo", "bar");

There are also new collector methods, toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap, to allow the elements of a stream to be collected into an unmodifiable collection. For example:

// Java 10
Stream.of("foo", "bar").collect(toUnmodifiableList());

// before Java 10
Stream.of("foo", "bar").collect(
    collectingAndThen(toList(), Collections::unmodifiableList));
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 10: Collecting a Stream into an Unmodifiable Collection

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
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

Leave a Reply

avatar

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

  Subscribe  
Notify of