2016-08-23 129 views
1

我曾嘗試這樣的代碼:Java的8 parallelStream(...) - >填寫ArrayList的

final List<ScheduleContainer> scheduleContainers = new ArrayList<>(); 
scheduleResponseContent.getSchedules().parallelStream().forEach(s -> scheduleContainers.addAll(s)); 

隨着parallelStream我得到一個任意或ArrayIndexOutOfBoundException一個NullPointerException因爲scheduleContainers某些條目爲空。

With ... .stream()...一切正常。 現在我的問題是,如果有可能解決這個問題,或者我誤用了parallelStream?

+0

你如何使用parallenStream加入列表?你可以請秀嗎? –

回答

3

不確定錯誤的原因,但有更好的方法可以使用Stream 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()); 
6

是的,你正在濫用parallelStream。首先,as you have already said twice in your previous question,你應該默認使用stream(),而不是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()); 
相關問題