2016-05-16 20 views
1

我有以下方法如何改變的foreach以拉姆達與並行流

private Set<Chapter> chapters; 
public long getCount() { 
    long count = 0; 
    for (Chapter chapter : chapters) count += chapter.getCount(); 
    return count; 
} 

,我想提高使用Java 8的功能,如流和lambda這個代碼,但我不能改變外部變量入λ ,所以我試圖欺騙,但這是一個可怕的解決方案。

public long getCount() { 
    final long[] count = {0}; 
    chapters.parallelStream().forEach(chapter -> count[0] += chapter.getCount()); 
    return count[0]; 
} 

你能幫我嗎?或者提供一些有用的鏈接給我。 對不起,如果它是重複的。

+0

這不是一個「可怕的解決方案」對數組元素的併發訪問*完全打破單排液* 。所以它根本就沒有解決方案。但是你已經[找到了正確的解決方案](http://stackoverflow.com/a/372​​49194/2711488)... – Holger

回答