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

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

问题描述

如果我在顺序流上调用collect(例如,从调用Collection.stream()),那么它会使用我传递的汇编参数来收集吗?我猜不是,但我在文档中看不到任何内容。如果我是正确的,那么似乎不幸的是必须提供我知道不会被使用的东西(如果我知道它是顺序流)。

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.

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

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天全站免登陆