:あなたは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例:
- ストリームではありません要素:Optional.empty()
- つの要素を返す:ちょうどすべてのアキュムレータを適用せずに要素を返します。
- 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