1

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
cbender
  • 2,231
  • 1
  • 14
  • 18
  • Where is the 'unnecessary operations' ! Both examples are working the same way; the first one collect data into list then create an unmodifiableList from the stream result, the second do exactly the same things. `collectingAndThen` operation is just a suite of final operations that make things works in a stream (pipeline) fashion way, you can achieve the same result using other methods – Abdelghani Roussi Jan 27 '19 at 11:58
  • 2
    Related: [Is collectingAndThen method enough efficient?](https://stackoverflow.com/q/47810524/1371329) The comment from Brian Goetz seems relevant here. – jaco0646 Jan 27 '19 at 15:39

0 Answers0