Skip to content

Collect Stream into Unmodifiable List, Set or Map with Java 8

Java 8 introduced a new Stream API that makes it easy to process collections of data. One of the most common tasks when working with streams is collecting the results into a List, Set, or Map. In this article, we’ll explore how to collect a stream into an unmodifiable List, Set, or Map with Java 8.

Step 1: Create a Stream

The first step is to create a Stream of data that you want to collect. You can create a Stream from a List, Set, or any other collection using the stream() method. Here’s an example:

List<String> myList = Arrays.asList("foo", "bar", "baz");
Stream<String> myStream =;

Step 2: Collect the Stream

Once you have a Stream, you can collect the elements into a List, Set, or Map using the collect() method. To make the resulting collection unmodifiable, we can use the Collections.unmodifiableXXX() method.

Here’s an example:

List<String> unmodifiableList = myStream.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

This code creates an unmodifiable List from the Stream. The Collectors.collectingAndThen() method first collects the elements into a mutable List using Collectors.toList(), and then wraps the result with Collections.unmodifiableList() to make it unmodifiable.

Similarly, you can create an unmodifiable Set like this:

Set<String> unmodifiableSet = myStream.collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));

And an unmodifiable Map like this:

Map<String, Integer> unmodifiableMap = myStream.collect(Collectors.collectingAndThen(Collectors.toMap(Function.identity(), String::length), Collections::unmodifiableMap));

Leave a Reply

Your email address will not be published. Required fields are marked *

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