Java 8 中的顺序流在调用 collect 时是否使用组合器参数? [英] Does a sequential stream in Java 8 use the combiner parameter on calling collect?

查看:17
本文介绍了Java 8 中的顺序流在调用 collect 时是否使用组合器参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在顺序流上调用 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);

这篇关于Java 8 中的顺序流在调用 collect 时是否使用组合器参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆