Java-8并行流(…)->;填充阵列列表

Java-8并行流(…)->;填充阵列列表,java-8,java-stream,Java 8,Java Stream,我尝试过以下代码: final List<ScheduleContainer> scheduleContainers = new ArrayList<>(); scheduleResponseContent.getSchedules().parallelStream().forEach(s -> scheduleContainers.addAll(s)); final List scheduleContainers=new ArrayList(); sched

我尝试过以下代码:

 final List<ScheduleContainer> scheduleContainers = new ArrayList<>();
 scheduleResponseContent.getSchedules().parallelStream().forEach(s -> scheduleContainers.addAll(s));
final List scheduleContainers=new ArrayList();
scheduleResponseContent.getSchedules().parallelStream().forEach->scheduleContainers.addAll;
使用parallelStream,我会得到ArrayIndexOutOfBoundException或NullpointerException,因为scheduleContainers中的某些条目为空

与。流()。。。一切正常。
我现在的问题是,是否有可能解决这个问题,或者我是否误用了并行流

不确定错误的原因,但有更好的方法使用流API从多个输入列表创建列表

final List<ScheduleContainer> scheduleContainers =
    scheduleResponseContent.getSchedules()
                           .parallelStream()
                           .flatMap(s->s.stream()) // assuming getSchedules() returns some 
                                                   // Collection<ScheduleContainer>, based 
                                                   // on your use of addAll(s)
                           .collect(Collectors.toList());
最终列表计划容器=
scheduleResponseContent.getSchedules()
.parallelStream()
.flatMap(s->s.stream())//假设getSchedules()返回一些
//收集,基于
//在您使用addAll时
.collect(Collectors.toList());

是的,您误用了parallelStream。首先,默认情况下应该使用stream(),而不是parallelStream()。并行化有一个内在的成本,这通常会使事情的效率低于简单的顺序流,除非您有大量的数据要处理,并且每个元素的处理都需要时间。在使用并行流之前,您应该有一个性能问题,并测量并行流是否解决了这个问题。正如你的帖子所显示的那样,还有更大的机会把并行流搞砸

阅读更多的论点

其次,此代码根本不是线程安全的,因为它使用多个并发线程添加到线程不安全的ArrayList中。如果使用collect()而不是forEach()为您创建最终列表,并自己向列表中添加内容,则是安全的

代码应该是

List<ScheduleContainer> scheduleContainers =
    scheduleResponseContent.getSchedules().
                           .stream()
                           .flatMap(s -> s.stream())
                           .collect(Collectors.toList());
列出计划容器=
scheduleResponseContent.getSchedules()。
.stream()
.flatMap(s->s.stream())
.collect(Collectors.toList());

如何使用parallenStream添加到列表中?你能给我看看吗?