More forms of reduce
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)reduce has three forms. The one-argument form has no identity and returns an Optional; the three-argument form adds a combiner so the result can have a different type and be built in parallel. All of them work only for values that are combined into new values, never for containers that are changed in place.
reduce without an identity returns an Optional
Some reductions have no natural neutral value. What is the identity for "the shorter of two names" or "the student with more marks"? Inventing one, like a fake student with -1 marks, is clumsy and can leak into the result.
Example 1 · reduce without an identity
import java.util.List;import java.util.Optional;
record Student(String name, int marks) {}
public class ReduceNoIdentityDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", 78), new Student("Priya", 92), new Student("Rohan", 85));
Optional<Student> topper = students.stream() .reduce((a, b) -> b.marks() > a.marks() ? b : a); System.out.println("Topper: " + topper.get().name());
Optional<String> shortest = List.of("Bengaluru", "Pune", "Chennai").stream() .reduce((a, b) -> b.length() < a.length() ? b : a); System.out.println("Shortest city: " + shortest.orElse("none"));
Optional<Integer> one = List.of(42).stream().reduce((a, b) -> a + b); Optional<Integer> none = List.<Integer>of().stream().reduce((a, b) -> a + b); System.out.println("One element: " + one); System.out.println("No elements: " + none); }}Topper: Priya Shortest city: Pune One element: Optional[42] No elements: Optional.empty
What this code does
- The first element is the starting value, so no fake "empty student" is needed. Each step keeps the better of the two, just like a loop that tracks the best so far.
- With one element,
reducereturns it without calling the accumulator. With none, there is nothing to start from, so the result isOptional.empty.List.<Integer>of()tells Java the element type of the empty list.
reduce(accumulator) skips the identity. It starts from the first element and combines the rest into it. Because an empty stream has no first element, it returns an Optional<T>: Optional.empty for no elements, and the single element itself when there is only one, without calling the accumulator. min, max and findFirst work the same way and return an Optional for the same reason. max(cmp) is really reduce((a, b) -> cmp.compare(a, b) >= 0 ? a : b) with a friendlier name.
The three-argument reduce and its combiner
The two-argument reduce(identity, accumulator) needs the result to have the same type as the elements: a Stream<Integer> reduces to an Integer. Sometimes you want a different type, like the total number of letters in a Stream<String>.
Example 2 · The three-argument reduce: a result of another type
import java.util.List;
record Order(String id, int amount) {}
public class ThreeArgReduceDemo { public static void main(String[] args) { List<String> names = List.of("Aarav", "Priya", "Siddharth", "Om");
int letters = names.stream().reduce( 0, // identity: Integer (count, name) -> count + name.length(), // accumulator: (Integer, String) -> Integer Integer::sum); // combiner: (Integer, Integer) -> Integer System.out.println("Total letters: " + letters);
List<Order> orders = List.of( new Order("O1", 450), new Order("O2", 1200), new Order("O3", 300)); int total = orders.stream().reduce( 0, (sum, o) -> sum + o.amount(), (left, right) -> { System.out.println("combiner called"); return left + right; }); System.out.println("Sequential total: " + total);
int parallelLetters = names.parallelStream() .reduce(0, (count, name) -> count + name.length(), Integer::sum); System.out.println("Parallel letters: " + parallelLetters); }}Total letters: 21 Sequential total: 1950 Parallel letters: 21
What this code does
- The elements are
Strings but the result is anInteger, which the two-argument form cannot do. The accumulator adds one name's length to the count; the combiner adds two counts. - "combiner called" never prints: a sequential stream has one chunk and never merges. On the parallel stream, each chunk counts its own names from 0 and
Integer::summerges the counts, giving the same 21.
reduce(identity, accumulator, combiner) allows that. The identity and the result have type U. The accumulator is a BiFunction<U, T, U>: it takes the result so far and one element and returns a new result, such as (count, name) -> count + name.length(). The combiner is a BinaryOperator<U> that merges two partial results, such as Integer::sum. The combiner is for parallel streams. Each chunk is reduced from the identity on its own thread, and the combiner then merges the chunk results. On a sequential stream there is only one chunk, so the combiner is never called, but you still must pass a correct one. The accumulator and combiner must agree: merging two partial results must give what one thread would have computed alone.
The operation must be associative
An operation is associative when the grouping does not change the answer: (a + b) + c equals a + (b + c). Addition, multiplication, max, min and String joining are associative.
Example 3 · Associative or not: sum versus subtraction
import java.util.List;
public class AssociativeDemo { public static void main(String[] args) { List<Integer> nums = List.of(10, 20, 30, 40, 50, 60, 70, 80);
System.out.println("Sum, sequential: " + nums.stream().reduce(0, Integer::sum)); System.out.println("Sum, parallel: " + nums.parallelStream().reduce(0, Integer::sum)); System.out.println("Subtract, sequential: " + nums.stream().reduce(0, (a, b) -> a - b)); System.out.println("Subtract, parallel: " + nums.parallelStream().reduce(0, (a, b) -> a - b)); }}Sum, sequential: 360 Sum, parallel: 360 Subtract, sequential: -360 Subtract, parallel: 0
What this code does
- Addition is associative, so any grouping gives 360. Subtraction is not: the sequential run computes 0 - 10 - 20 - ... = -360, while the parallel run subtracts chunk results from each other and got 0 here.
- There is no error message. The only protection is to use
reducewith associative operations:+,*,max,min, String joining.
Subtraction and division are not: (10 - 5) - 2 is 3, but 10 - (5 - 2) is 7. A parallel stream groups elements in a different way from a sequential one. With an associative operation and a neutral identity, every grouping gives the same answer. With subtraction, the answer depends on how the data was split, so it can change with the number of CPU cores.
So the rules for every form of reduce are: the identity is neutral, the operation is associative, and the functions have no side effects.
Trap: reducing into a StringBuilder or a list
reduce is designed for immutable results: each step returns a new value and leaves the old one untouched. a + b makes a new number; s1 + s2 makes a new String.
Example 4 · Trap: a StringBuilder as the identity
import java.util.List;
public class MutableReduceTrapDemo { public static void main(String[] args) { List<String> codes = List.of("A", "B", "C", "D", "E", "F", "G", "H");
StringBuilder seq = codes.stream() .reduce(new StringBuilder(), (sb, s) -> sb.append(s), (a, b) -> a.append(b)); System.out.println("Sequential: " + seq);
StringBuilder par = codes.parallelStream() .reduce(new StringBuilder(), (sb, s) -> sb.append(s), (a, b) -> a.append(b)); System.out.println("Parallel length: " + par.length()); System.out.println("Parallel starts: " + par.substring(0, 12)); }}Sequential: ABCDEFGH Parallel length: 432 Parallel starts: FEFEHGFEFEHG
What this code does
- Sequentially it looks perfect, which is what makes the bug dangerous. There is only one
StringBuilder: the identity object. In parallel, every chunk appends to that same object, and the combiner appends it to itself, so 8 letters became 432 characters. reduceexpects each step to return a new value.appendchanges the old one and returns it. Any mutable identity, such as anew ArrayList<>(), breaks the same way.
A StringBuilder or an ArrayList is mutable: append and add change the same object. If the identity is new StringBuilder(), there is only one builder, and on a parallel stream every chunk appends into it at once. The combiner then appends the builder to itself. The result is garbage, and only the parallel run shows it. This is called a mutable reduction, and Java has a separate operation for it: collect. It takes a supplier such as StringBuilder::new, so each chunk gets its own fresh container, and a combiner merges the containers at the end.
When collect is the right tool
Use reduce when the result is a single immutable value: a number, a String built from a few parts, a record, or one chosen element. Use collect when the result is a container you fill: a list, a set, a map or a StringBuilder.
Example 5 · The fix: collect gives each chunk its own container
import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;
public class CollectFixDemo { public static void main(String[] args) { List<String> codes = List.of("A", "B", "C", "D", "E", "F", "G", "H");
StringBuilder sb = codes.parallelStream() .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append); System.out.println("collect into StringBuilder: " + sb);
ArrayList<String> lower = codes.parallelStream() .map(String::toLowerCase) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); System.out.println("collect into ArrayList: " + lower);
String joined = codes.parallelStream().collect(Collectors.joining("-")); System.out.println("Collectors.joining: " + joined);
String byReduce = codes.parallelStream().reduce("", String::concat); System.out.println("reduce with String::concat: " + byReduce); }}collect into StringBuilder: ABCDEFGH collect into ArrayList: [a, b, c, d, e, f, g, h] Collectors.joining: A-B-C-D-E-F-G-H reduce with String::concat: ABCDEFGH
What this code does
collect(supplier, accumulator, combiner)calls the supplier (StringBuilder::new,ArrayList::new) once per chunk, so threads never share a container. The combiner (append,addAll) joins the chunk containers in order.reduce("", String::concat)is also correct in parallel, because Strings are immutable and concatenation is associative. It creates a new String at every step, though, so for many partsCollectors.joiningis the better tool.
- A total, product, maximum or chosen element →
reduce(orsum,max). - A list of results →
toList()orcollect(Collectors.toList()). - A String joined from many parts →
collect(Collectors.joining(", ")). - Your own container →
collect(Supplier, accumulator, combiner), such ascollect(StringBuilder::new, StringBuilder::append, StringBuilder::append).
toList() and Collectors.toList(). The Stream Collectors module covers joining, groupingBy and the rest.Next step
Check your understanding
12 quick questions