Sub topic 11
Combining Elements with reduce
Many questions about a list have a single number or value as their answer. What is the total of these prices? What is the largest score? What do these words spell when joined? Each question takes many elements and combines them into one result. In the Stream API, this kind of operation is called a reduction. A reduction is a terminal operation that combines all the elements of a stream into one value.
This chapter shows the reduce method, the general tool for reductions. It also covers the shortcuts, such as count, that save you from writing reduce yourself.
The idea: combine two at a time
reduce never looks at all the elements at once. It combines two values, then combines that result with the next element, and keeps going until no elements are left.
Here is how adding up 1, 2, 3, 4, 5 works, starting from 0:
| Step | Running result | Next element | New result |
|---|---|---|---|
| 1 | 0 | 1 | 1 |
| 2 | 1 | 2 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 6 | 4 | 10 |
| 5 | 10 | 5 | 15 |
The running result is often called the accumulator: it holds the partial answer built so far.
reduce with an identity value
The most common form of reduce takes two arguments:
- An identity value. This is the starting value. It is also the answer when the stream is empty.
- An accumulator function. This is a function that takes two values and returns their combination.
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, Integer::sum);
int max = numbers.stream().reduce(Integer.MIN_VALUE, Integer::max);
System.out.println(sum); // 15
System.out.println(max); // 5
}
}Integer::sum is a method reference. It means the same as the lambda (a, b) -> a + b. Integer::max means (a, b) -> Math.max(a, b), so it keeps the bigger of the two values.
The max example starts from Integer.MIN_VALUE, the smallest possible int. Any real element is at least that large, so the first comparison always keeps the element.
Choosing the right identity
The identity must leave other values unchanged when you combine it with them. For addition that value is 0, because x + 0 is x. For multiplication it is 1, because x * 1 is x.
| Operation | Accumulator | Identity |
|---|---|---|
| Sum | `Integer::sum` | `0` |
| Product | `(a, b) -> a * b` | `1` |
| Maximum | `Integer::max` | `Integer.MIN_VALUE` |
| Minimum | `Integer::min` | `Integer.MAX_VALUE` |
| Join strings | `String::concat` | `""` |
reduce without an identity
Sometimes no identity value makes sense. What is the largest element of an empty list? There is no good answer. For these cases, reduce has a one-argument form that takes only the accumulator. It returns an Optional, a container that either holds a value or is empty.
import java.util.List;
import java.util.Optional;
public class ReduceOptionalExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(3, 7, 2);
Optional<Integer> largest = numbers.stream().reduce(Integer::max);
System.out.println(largest.orElse(-1)); // 7
List<Integer> empty = List.of();
Optional<Integer> none = empty.stream().reduce(Integer::max);
System.out.println(none.isPresent()); // false
System.out.println(none.orElse(-1)); // -1
}
}With no identity, the first element becomes the starting value. If the stream has no elements, the result is an empty Optional. You handle it with orElse or the other Optional methods from the earlier chapter.
The rule of associativity
The accumulator function should be associative. An operation is associative when the grouping of the steps does not change the answer:
- Addition is associative:
(1 + 2) + 3equals1 + (2 + 3). Both are 6. - Subtraction is not:
(10 - 4) - 3is 3, but10 - (4 - 3)is 9.
A sequential stream always combines from left to right, so a non-associative function may happen to work there. A parallel stream splits the elements into groups and combines the groups in any order, so a non-associative function gives wrong answers. Using only associative functions keeps your code correct no matter how the stream runs.
The three-argument form
The first two forms produce a result of the same type as the elements. If you add Integer values, you get an Integer back. Sometimes you want a different type. For example, you might want the total number of letters in a list of String words.
The three-argument reduce handles this. It takes an identity, an accumulator that adds one element to the running result, and a combiner that merges two partial results. The combiner is only used by parallel streams, but you must supply it either way.
import java.util.List;
public class ReduceThreeArgs {
public static void main(String[] args) {
List<String> words = List.of("tea", "coffee", "milk");
int totalLetters = words.stream()
.reduce(0,
(count, word) -> count + word.length(),
Integer::sum);
System.out.println(totalLetters); // 13
}
}This form is harder to read. Usually a map step followed by a simple sum is clearer:
import java.util.List;
public class MapThenReduce {
public static void main(String[] args) {
List<String> words = List.of("tea", "coffee", "milk");
int totalLetters = words.stream()
.map(String::length)
.reduce(0, Integer::sum);
System.out.println(totalLetters); // 13
}
}Ready-made reductions
Some reductions are so common that streams provide them as methods. They are shorter and easier to read than reduce.
import java.util.Comparator;
import java.util.List;
public class BuiltInReductions {
public static void main(String[] args) {
List<Integer> numbers = List.of(4, 9, 1, 6);
long count = numbers.stream().count();
int largest = numbers.stream().max(Comparator.naturalOrder()).orElse(0);
int smallest = numbers.stream().min(Comparator.naturalOrder()).orElse(0);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println(count); // 4
System.out.println(largest); // 9
System.out.println(smallest); // 1
System.out.println(sum); // 20
}
}A few details are worth noticing:
countreturns along, not anint.maxandminneed aComparator, which is an object that decides which of two values comes first. They return anOptional, because an empty stream has no largest element.sumexists only on primitive streams such asIntStream.mapToIntconverts the stream to one. A later chapter covers primitive streams.
Use reduce when no ready-made method fits, such as for a product or a custom combination.
Exercises
Exercise
What does List.of(2, 3, 4).stream().reduce(1, (a, b) -> a * b) return, and why is 1 the identity here?
Show answer
It returns 24 (1 × 2 × 3 × 4). The identity is 1 because multiplying any number by 1 leaves it unchanged, and 1 is also the correct result for an empty stream.
Exercise
Why does List.of(5, 8).stream().reduce(Integer::sum) return an Optional<Integer> instead of an Integer?
Show answer
This form has no identity value. If the stream were empty, there would be no value to return, so the result is wrapped in an Optional that can be empty.
Exercise
A teammate writes numbers.stream().reduce(0, (a, b) -> a - b) to subtract all the numbers. What is the problem?
Show answer
Subtraction is not associative, so the grouping changes the answer. The code may seem to work on a sequential stream but gives wrong results on a parallel stream. Sum the numbers with Integer::sum and subtract that sum from the starting value instead.
Exercise
Write a pipeline that joins List.of("a", "b", "c") into the string "abc" using reduce.
Show answer
List.of("a", "b", "c").stream().reduce("", String::concat) returns "abc". The empty string is the identity because joining "" to any string leaves it unchanged.