Functional programming Flashcards
What is a Stream.reduce() operation?
What elements it consist of?
When we need Combiner?
[1] reduction stream operations allow us to produce one single result from a sequence of elements, by repeatedly applying a combining operation to the elements in the sequence.
[2] Before we look deeper into using the Stream.reduce() operation, let’s break down the operation’s participant elements into separate blocks. That way, we’ll understand more easily the role that each one plays:
a) Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty b) Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream c) 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
c) EXamples
[c1] int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);
[c2] We need to use combiner when type of accumulator argument and next element in the stream have the same type or when we use parallelStream:
int result = users.stream()
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65);