Monthly Archives: April 2015

How to collect Immutable Collection in Java

To begin with this story, let’s first have a look at how to creat a List from Stream in Java

List<String> sublist = list
  .stream()
  .filter(...)
  .collect(Collectors.toList());

This works perfectly fine but what if we want the list to be immutable? We could do this

List<String> immutableSubList = Collections.unmodifiableList(sublist);

or if we would like to use Guava ImmutableList, we could do

ImmutableList<String> immutableSubList = ImmutableList.copyOf(sublist);

However this is a bit awkward to use since the list will be copied one more time. If we want to do this in a lot of places throughout the code base, it is not fluid. Instead, what we want is

ImmutableList<String> sublist = list
  .stream()
  .filter(...)
  .collect(ImmutableCollectors.toList());

This post will discuss how to create the Collector of ImmutableList.

Collector

To create a Collector, we will use the static method of.

public static<t, A, R> Collector<T, A, R> of(
  Supplier<A> supplier,
  BiConsumer<A, T> accumulator,
  BinaryOperator<A> combiner,
  Function<A, R> finisher,
  Characteristics... characteristics);

read more