Collectors.toUnmodifiableList in java-10
Additionally to clear out a documented difference between the two(collectingAndThen
vs toUnmodifiableList
) implementations :
The
Collectors.toUnmodifiableList
would return a Collector that disallows null values and will throwNullPointerException
if it is presented with anull
value.
static void additionsToCollector() {
// this works fine unless you try and operate on the null element
var previous = Stream.of(1, 2, 3, 4, null)
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
// next up ready to face an NPE
var current = Stream.of(1, 2, 3, 4, null).collect(Collectors.toUnmodifiableList());
}
and furthermore, that's owing to the fact that the former constructs an instance of Collections.UnmodifiableRandomAccessList
while the latter constructs an instance of ImmutableCollections.ListN
which adds to the list of attributes brought to the table with static factory methods.
With Java 10, this is much easier and a lot more readable:
List<Integer> result = Arrays.asList(1, 2, 3, 4)
.stream()
.collect(Collectors.toUnmodifiableList());
Internally, it's the same thing as Collectors.collectingAndThen
, but returns an instance of unmodifiable List
that was added in Java 9.