我试过这样的代码:
final List<ScheduleContainer> scheduleContainers = new ArrayList<>();
scheduleResponseContent.getSchedules().parallelStream().forEach(s -> scheduleContainers.addAll(s));使用scheduleContainers,我可以得到一个ArrayIndexOutOfBoundException或一个NullpointerException,因为在parallelStream中的一些条目是空的。
用.stream()..。一切都很好。我现在的问题是,是否有可能修复这个问题,还是我误用了parallelStream?
发布于 2016-08-23 05:52:35
是的,你在滥用parallelStream。首先,在默认情况下,您应该使用as you have already said twice in your previous question,而不是parallelStream()。并行具有内在的成本,这通常会使事情比简单的顺序流效率低,除非您有大量的数据量要处理,并且每个元素的处理过程需要时间。在使用并行流之前,您应该有一个性能问题,并度量它是否解决了它。还有一个更大的机会搞砸一个平行流,正如你的帖子所显示的。
阅读Should I always use a parallel stream when possible?获取更多参数。
第二,这段代码根本不是线程安全的,因为它使用多个并发线程添加到线程不安全的ArrayList中。如果使用collect()来为您创建最终列表,而不是使用forEach(),然后自己向列表中添加内容,则可能是安全的。
代码应该是
List<ScheduleContainer> scheduleContainers =
scheduleResponseContent.getSchedules().
.stream()
.flatMap(s -> s.stream())
.collect(Collectors.toList());发布于 2016-08-23 05:48:26
不确定错误的原因,但是有更好的方法可以使用Stream从多个输入列表创建列表。
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());https://stackoverflow.com/questions/39093178
复制相似问题