Java 8 中的顺序流在调用 collect 时是否使用组合器参数?

2022-01-22 00:00:00 java-8 java java-stream

如果我在顺序流上调用 collect(例如,通过调用 Collection.stream()),那么它会使用我传递给 collect 的组合器参数吗?我想不是,但我在文档中什么也没看到.如果我是正确的,那么必须提供一些我知道不会被使用的东西(如果我知道它是一个顺序流)似乎很不幸.

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 in the documentation. If I'm correct, then it seems unfortunate to have to supply something that I know will not be used (if I know it is a sequential stream).

推荐答案

记住要针对接口规范进行开发——而不是针对实现.下一个 Java 版本的实现可能会发生变化,而规范应该保持稳定.

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.

规范不区分顺序流和并行流.因此,您应该假设可能会使用 combiner.实际上,有很好的例子表明用于顺序流的 combiners 可以提高性能.例如,以下 reduce 操作连接字符串列表.在没有 combiner 的情况下执行代码具有二次复杂度.使用 combiner 的智能执行可以大大减少运行时间.

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);

相关文章