puv*_*uvi 5 java parallel-processing reduce java-stream
我正在尝试了解 reduce 方法。如果我使用 reduce 和 stream() 我得到_ab,如果我使用 reduceparallelStream()我得到_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){ }
}
}
Run Code Online (Sandbox Code Playgroud)
如果你通过了有效的论点,那就会了。阅读Javadoc:
该
identity值必须是累加器函数的标识。这意味着对于所有的t,accumulator.apply(identity, t)都等于t。
您传递的输入并非如此;"_".concat(t)不等于t. 由于您传递了无效参数,因此该方法的行为是未定义的,并且该方法可以执行任何操作,包括使恶魔从您的鼻子中射出。
我很难说出你真正想要的行为,尽管我怀疑你想要.collect(joining("_"))。不过,您实际上还没有告诉我们您想要的输出。
| 归档时间: |
|
| 查看次数: |
2317 次 |
| 最近记录: |