该方法需要3个参数
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
第一个 supplier 用来包装返回结果的容器
也就是你需要什么返回值 这里创建一个什么对象
第二个 accumulator 用来处理每一个元素,
这个如果是单纯的stream是有顺序的,如果是并行流则是没有顺序的.
第三个combiner 如果不是使用并行流 则可以直接传null 因为不会进行操作
可以看下面代码 并行流虽然也是多线程但是用collect最终得出结果还是有顺序的
int[] resultText = "123456789".chars().map(i -> Integer.parseInt(String.valueOf((char) i))).toArray();
// StringBuilder result = Arrays.stream(resultText).collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
StringBuilder result = Arrays.stream(resultText).parallel().collect(StringBuilder::new, (sb, s) -> {
System.out.println(Thread.currentThread().getName()+"---" + sb.toString());
System.out.println(Thread.currentThread().getName()+"***" + s);
sb.append(s);
}, (sb, s) -> {
System.out.println(Thread.currentThread().getName()+"&&&" + sb.toString());
System.out.println(Thread.currentThread().getName()+"###" + s);
sb.append(s);
});
System.out.println(result);
输出结果
main---
main***6
ForkJoinPool.commonPool-worker-9---
ForkJoinPool.commonPool-worker-9***5
ForkJoinPool.commonPool-worker-9&&&5
ForkJoinPool.commonPool-worker-9###6
ForkJoinPool.commonPool-worker-3---
ForkJoinPool.commonPool-worker-3***7
ForkJoinPool.commonPool-worker-7---
ForkJoinPool.commonPool-worker-7***8
ForkJoinPool.commonPool-worker-5---
ForkJoinPool.commonPool-worker-5***3
ForkJoinPool.commonPool-worker-5---
ForkJoinPool.commonPool-worker-5***4
ForkJoinPool.commonPool-worker-5&&&3
ForkJoinPool.commonPool-worker-5###4
ForkJoinPool.commonPool-worker-5---
ForkJoinPool.commonPool-worker-5***1
ForkJoinPool.commonPool-worker-5---
ForkJoinPool.commonPool-worker-5***9
ForkJoinPool.commonPool-worker-5&&&8
ForkJoinPool.commonPool-worker-5###9
ForkJoinPool.commonPool-worker-5&&&7
ForkJoinPool.commonPool-worker-5###89
ForkJoinPool.commonPool-worker-5&&&56
ForkJoinPool.commonPool-worker-5###789
ForkJoinPool.commonPool-worker-3---
ForkJoinPool.commonPool-worker-3***2
ForkJoinPool.commonPool-worker-3&&&1
ForkJoinPool.commonPool-worker-3###2
ForkJoinPool.commonPool-worker-3&&&12
ForkJoinPool.commonPool-worker-3###34
ForkJoinPool.commonPool-worker-3&&&1234
ForkJoinPool.commonPool-worker-3###56789
123456789
本文深入探讨了Java中Stream的collect方法,详细解析了supplier、accumulator和combiner三个参数的作用。通过实例展示了并行流在收集操作中的行为,尽管并行但结果依然保持顺序。示例代码中,将字符数组转换为整数,再用StringBuilder收集,展示了并行流处理过程中线程间的交互和最终顺序保证。
1245

被折叠的 条评论
为什么被折叠?



