Recently, while developing examples for the groupingBy() guide, I discovered handy JDK 10 additions to the Stream API – Collectors allowing collecting Stream pipelines into unmodifiable data structures.
In this super-short article, we’ll have a look at them.
Immutable Collectors
By default, most Stream API Collectors represent mutable collection strategies – but what happens if one wants to collect elements to an immutable data structure?
The first thing that comes to mind is to pass an instance of an immutable collection to the Collectors.toCollection() collector, but it quickly turns out to be a way to nowhere since the provided collection is… immutable and can’t be changed after creation:
Stream.of(42).collect(Collectors.toCollection(List::of)); // result java.lang.UnsupportedOperationException at ...ImmutableCollections.uoe(ImmutableCollections.java:71) at ...ImmutableCollections$AbstractImmutableList.add(ImmutableCollections.java:77) at ...stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169) at ...stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
Technically, this wouldn’t be a problem if Collections/Stream API was designed in an immutable-friendly manner, but we need to play the cards we were dealt.
Before JDK 10
Luckily, before JDK 10, the pragmatic solution to the above problem was quite straightforward. One could simply collect a Stream as always, and then convert the result into an unmodifiable structure by leveraging the collectingAndThen collector:
var unmodifiableList = Stream.of(42) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
Another (in most cases – overkill) solution was to implement a custom collector, for example:
public class CustomUnmodifiableListCollector<T> implements Collector<T, ArrayList<T>, List<T>> { private CustomUnmodifiableListCollector() { } public static <T> Collector<T, ?, List<T>> toUnmodifiableList() { return new CustomUnmodifiableListCollector<>(); } @Override public Supplier<ArrayList<T>> supplier() { return ArrayList::new; } @Override public BiConsumer<ArrayList<T>, T> accumulator() { return ArrayList::add; } @Override public BinaryOperator<ArrayList<T>> combiner() { return (ts, ts2) -> Stream.concat(ts.stream(), ts2.stream()) .collect(Collectors.toCollection(ArrayList::new)); } @Override public Function<ArrayList<T>, List<T>> finisher() { return Collections::unmodifiableList; } @Override public Set<Characteristics> characteristics() { return Set.of(); } }
After JDK 10
JDK 10 finally brought dedicated native collectors to the table which make the experience much smoother:
All of the above return new immutable implementations introduced in JDK 9.
So, the job is now as easy as:
var collect = Stream.of(42) .collect(Collectors.toUnmodifiableList());
…the interesting fact is that if you look at the implementation, you will see that they don’t use builders, but simply repackage the result just like we did in the section above:
public static <T> Collector<T, ?, List<T>> toUnmodifiableList() { return new CollectorImpl<>( (Supplier<List<T>>) ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, (list) -> (List<T>)List.of(list.toArray()), CH_NOID); }
Sources
All the above examples can be found in my GitHub project.