reduce folds a stream into one value. The identity must be neutral and the operation associative, otherwise a parallel run gives a different answer.
var words = List.of("java", "streams", "api");
int totalChars = words.stream().reduce(0, (sum, w) -> sum + w.length(), Integer::sum);
System.out.println("total characters = " + totalChars);
Optional<String> longest = words.stream().reduce((a, b) -> a.length() >= b.length() ? a : b);
System.out.println("longest = " + longest.orElse("none"));
total characters = 14
longest = streams
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30