Like Stream.reduce Stream (BinaryOperator <T>)
The following code works fine, without the need to initialize it.
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
How does he know that the first battery is +so that it initializes a new amount = 0, and the second battery is *that it initializes a new amount = 1?
+6
3 answers
1-argument reducedoes not start with an identifier value (0 or 1). It only affects the values ββin your stream. If you look at javadoc , it will even display the equivalent code:
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();
+7
This is his API specification:
Optional<T> java.util.stream.Stream.reduce(BinaryOperator<T> accumulator)
: a ,
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();
:
- : return Optional.empty()
- : .
- : .
:
// 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
+3