Does a sequential stream in Java 8 use the combiner parameter on calling collect?

前端 未结 1 1962
半阙折子戏
半阙折子戏 2020-12-05 10:24

If I call collect on a sequential stream (eg. from calling Collection.stream()) then will it use the combiner parameter I pass to collect? I presume not but I see nothing i

相关标签:
1条回答
  • 2020-12-05 10:54

    Keep in mind to develop against interface specifications -- not against the implementation. The implementation might change with the next Java version, whereas the specification should remain stable.

    The specification does not differentiate between sequential and parallel streams. For that reason, you should assume, that the combiner might be used. Actually, there are good examples showing that combiners for sequential streams can improve the performance. For example, the following reduce operation concatenates a list of strings. Executing the code without combiner has quadratic complexity. A smart execution with combiner can reduce the runtime by magnitudes.

    List<String> tokens = ...;
    String result = tokens.stream().reduce("", String::concat, String::concat);
    
    0 讨论(0)
提交回复
热议问题