【问题标题】:why Combiner is not making affect on output? [duplicate]为什么组合器对输出没有影响? [复制]
【发布时间】:2017-07-27 08:45:28
【问题描述】:

以下代码输出一直是24。

public static void main(String[] args) throws InterruptedException {
    List<String> list = new ArrayList<String>();
    list.add("java");
    list.add("php");
    list.add("python");
    list.add("perl");
    list.add("c");
    list.add("lisp");
    list.add("c#");
    int s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> 0);
    System.out.println(s);
    s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x - y);
    System.out.println(s);
    s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x * y);
    System.out.println(s);

}   

问题是为什么组合器会影响我的代码。

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    combiner 用于并行流。

    但是即使您添加parallel,您的代码也可能存在其他问题。他们都违反了一些规则……具体来说:

    另外,combiner 函数必须与 accumulator 函数兼容;对于所有 u 和 t,以下必须成立

     combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
    

    您的组合器违反了这一点,因此取决于您拥有的 CPU 数量 - 您会得到不同的结果 - 这显然是错误的。

    【讨论】:

    • 你能解释更多关于 combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 的信息吗??
    • 谢谢,我对同一本 OCJP 书也有同样的疑问。我在问这个句子>>表示你是什么以及表达是什么 combiner.apply(u, accumulator.apply(identity, t))
    • @HasnainAliBohra ut 将是流中的两个随机元素(任意两个元素); accumulatorcombinerreduce 的第二个和第三个参数
    • 感谢你值得支持。
    【解决方案2】:

    如果减少并行Streamcombiner 会影响结果。对于连续的Stream,不需要组合部分结果。

    例如,当我在您的代码中将 stream() 更改为 parallelStream() 时,我得到:

    0
    6
    2304
    

    当然,您提供的所有组合器都是坏组合器。您应该提供一个影响reduce的最终结果的组合器。

    【讨论】:

    • 你不喜欢这个吗?当您知道自己是对的但仍然投反对票时? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2019-09-28
    相关资源
    最近更新 更多