2017-07-27 54 views
2

以下代碼輸出總是24。爲什麼Combiner不會對輸出產生影響?

public static void main(String[] args) throws InterruptedException { 
    List<String> list = new ArrayList<String>(); 
    list.add("java"); 
    list.add("php"); 
    list.add("python"); 
    list.add("perl"); 
    list.add("c"); 
    list.add("lisp"); 
    list.add("c#"); 
    int s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> 0); 
    System.out.println(s); 
    s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x - y); 
    System.out.println(s); 
    s = list.stream().reduce(0, (x, y) -> x + y.length(), (x, y) -> x * y); 
    System.out.println(s); 

} 

問題是爲什麼組合器影響我的代碼。如果減少並行Stream

回答

5

組合器是僅用於並行流

但也有可能是其他問題與您的代碼,即使你加parallel。他們都違反了一些規則...具體來說:

此外,組合功能必須兼容累加器功能;所有的U和T,下面必須持有

combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 

和你合違反這一點,所以這取決於CPU的數量你有 - 你會得到不同的結果 - 這顯然是錯誤的。

+0

你能解釋更多關於** combiner.apply(u,accumulator.apply(identity,t))== accumulator.apply(u,t)** ?? –

+0

@HasnainAliBohra https://stackoverflow.com/questions/45054372/what-do-the-stream-reduce-requirements-exactly-entail/45054892#45054892 – Eugene

+0

由於我是具有相同疑問形成同一OCJP book.Im問句子>>意思是u和什麼表達** combiner.apply(U,accumulator.apply(身份,t))的**是 –

2

combiner會影響結果。對於連續的Stream,不需要合併部分結果。

例如,當我在你的代碼更改stream()parallelStream(),我得到:

0 
6 
2304 

當然,你所提供的組合是壞的組合。你應該提供一個組合器,不會影響reduce的最終結果

+3

你不喜歡這個嗎?當你知道你是對的,仍然得到一個投票? :) – Eugene

相關問題