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
source share
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
source

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

As long as your stream has one or more elements, you do not need an identifier value. The first abbreviation returns 2+3, which is equivalent 0+2+3. The second returns 2*3, which is equivalent 1*2*3.

+2
source

All Articles