reduce in stream in java code example
Example: reduce in stream in java
// Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty
// Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream
// Combiner – a function used to combine the partial result of the reduction operation when the reduction is parallelized or when there's a mismatch between the types of the accumulator arguments and the types of the accumulator implementation
import java.util.*;
import java.util.stream.*;
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers
.stream()
.reduce(0, (subtotal, element) -> subtotal + element); // Didn't use a combiner here
// A combiner should be used when objects are used in accumulator parameters
// Only then, it works
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream()
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
// Integer::sum is a combiner which is a function for the desired operation.