gpt4 book ai didi

java 8 reduce with parallelStream 和 stream

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:07 25 4
gpt4 key购买 nike

<分区>

我正在尝试理解 reduce 方法。如果我将 reduce 与 stream() 结合使用,我会得到 _ab,如果我将 reduce 与 parallelStream() 结合使用,我会得到 _a_b。无论我们使用 parallelStream 还是 stream,reduce 的输出不应该相同吗?

import java.util.*;
import java.util.stream.*;

class TestParallelStream{

public static void main(String args[]){
List<String> l = Arrays.asList("a","b","c","d");
String join=l.stream()
.peek(TestParallelStream::sleepFor)
.reduce("_",(a,b) -> a.concat(b));
System.out.println(join);
}

public static void sleepFor(String w){
System.out.println("inside thread:"+w);
try{
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){ }
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com