reduce in stream in java

Solutions on MaxInterview for reduce in stream in java by the best coders in the world

showing results for - "reduce in stream in java"
Louisa
03 Oct 2018
1// Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty
2// Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream
3// 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
4
5import java.util.*; 
6import java.util.stream.*;
7
8List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
9int result = numbers
10  .stream()
11  .reduce(0, (subtotal, element) -> subtotal + element); // Didn't use a combiner here
12
13// A combiner should be used when objects are used in accumulator parameters
14// Only then, it works
15
16List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
17int result = users.stream()
18  .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
19// Integer::sum is a combiner which is a function for the desired operation.
20