2017-05-22 7 views
6

次のコードは、初期化する必要なく完全に動作します。それは= 1新しい合計に初期化する必要がありますように、それは新しい合計= 0に初期化する必要があり、第二アキュムレータは*あるようにどのようにそれが最初のアキュムレータが+であることを知っているんStream.reduce(BinaryOperator <T>アキュムレータ)はどのようにして

int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a+b).get(); // sum = 5 
int sum=Stream.of(2,3).reduce((Integer a,Integer b)->a*b).get(); // sum = 6 

答えて

7

1つの引数reduceは、ID値(0または1)で開始しません。ストリーム内の値に対してのみ動作します。

Optional<T> java.util.stream.Stream.reduce(BinaryOperator<T> accumulator) 

返します:これは、そのAPI仕様です

boolean foundAny = false; 
T result = null; 
for (T element : this stream) { 
    if (!foundAny) { 
     foundAny = true; 
     result = element; 
    } 
    else 
     result = accumulator.apply(result, element); 
} 
return foundAny ? Optional.of(result) : Optional.empty(); 
2

ストリームに1つ以上の要素がある限り、ID値は必要ありません。最初の還元は2+3を返します。これは0+2+3に相当します。 2番目は2*3を返します。これは1*2*3に相当します。

3

:あなたはjavadocを見れば、それも同等のコードを示しますオプションが削減

としての結果を記述するそのjavadocごとに、同等のコードは次のとおりです。

boolean foundAny = false; 
T result = null; 
for (T element : this stream) { 
    if (!foundAny) { 
     foundAny = true; 
     result = element; 
    } 
    else 
     result = accumulator.apply(result, element); 
} 
return foundAny ? Optional.of(result) : Optional.empty(); 

3例:

  1. ストリームではありません要素:Optional.empty()
  2. つの要素を返す:ちょうどすべてのアキュムレータを適用せずに要素を返します。
  3. 2つ以上の要素:すべての要素にアキュムレータを適用し、結果を返します。この低減方法の

詳細例:

// Example 1: No element 
Integer[] num = {}; 
Optional<Integer> result = Arrays.stream(num).reduce((Integer a, Integer b) -> a + b); 
System.out.println("Result: " + result.isPresent()); // Result: false 

result = Arrays.stream(num).reduce((Integer a, Integer b) -> a * b); 
System.out.println("Result: " + result.isPresent()); // Result: false 

// Example 2: one element 
int sum = Stream.of(2).reduce((Integer a, Integer b) -> a + b).get(); 
System.out.println("Sum: " + sum); // Sum: 2 

int product = Stream.of(2).reduce((Integer a, Integer b) -> a * b).get(); 
System.out.println("Product: " + product); // Product: 2 

// Example 3: two elements 
sum = Stream.of(2, 3).reduce((Integer a, Integer b) -> a + b).get(); 
System.out.println("Sum: " + sum); // Sum: 5 

product = Stream.of(2, 3).reduce((Integer a, Integer b) -> a * b).get(); 
System.out.println("Product: " + product); // Product: 6 
関連する問題