I've been seeing a lot of Stream
examples that use the Collectors
collectingAndThen
method in the terminal collect
operation. In a lot of these examples, the finisher
argument (for the 2nd parameter of the collectingAndThen
method) is a relatively simple call that shouldn't require the collectingAndThen
method because the resulting data structure from just using the first Collector
can be passed as an argument to the method in the finisher
parameter, and in-fact calling collectingAndThen
adds unnecessary operations.
For example (using the actual example in the Oracle documentation for collectingAndThen
, I know this is an extremely overly simple example but I've seen a lot of people on StackOverflow and other sites doing similar things with just 1 or 2 intermediary operations and its simplicity isn't the factor in question here)-
List<String> people =
people.stream().collect(collectingAndThen(toList(), Collections::unmodifiableList));
Accomplishes the same as-
List<String> people = Collections.unmodifiableList(
people.stream().collect(toList());
But using collectingAndThen
in the first example is adding unnecessary operations (you can look at the OpenJDK implementation of Collectors
to see its source code).
I understand there are necessary times to use the method, and sometimes it is cleaner. But is it being improperly used in cases that are like this or am I missing something?