java 8 使用 parallelStream 和流减少
java 8 reduce with parallelStream and stream
我正在尝试了解 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){ }
}
}
如果您传递了有效的参数,就会是。阅读 Javadoc:
The identity
value must be an identity for the accumulator function. This means that for all t
, accumulator.apply(identity, t)
is equal to t
.
您传递的输入不是这种情况; "_".concat(t)
不等于 t
。由于您传递了无效参数,因此该方法的行为未定义,并且允许该方法执行任何操作,包括 making demons shoot out of your nose.
我很难说出你实际上想要的行为,尽管我怀疑你想要.collect(joining("_"))
。不过,您实际上并没有告诉我们您想要的输出。
我正在尝试了解 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){ }
}
}
如果您传递了有效的参数,就会是。阅读 Javadoc:
The
identity
value must be an identity for the accumulator function. This means that for allt
,accumulator.apply(identity, t)
is equal tot
.
您传递的输入不是这种情况; "_".concat(t)
不等于 t
。由于您传递了无效参数,因此该方法的行为未定义,并且允许该方法执行任何操作,包括 making demons shoot out of your nose.
我很难说出你实际上想要的行为,尽管我怀疑你想要.collect(joining("_"))
。不过,您实际上并没有告诉我们您想要的输出。