Java 8 (LTS) · Topic 8 of 12
reduce
Definition​
reduce combines all items of a stream into a single value by applying an operation again and again, such as adding numbers. It needs a starting value and a rule for combining two values.
Example code​
Adding numbers, and finding the longest word
import java.util.List;
class Demo {
public static void main(String[] args) {
List<Integer> numbers = List.of(4, 8, 15, 16, 23, 42);
int sum = numbers.stream().reduce(0, (a, b) -> a + b); // start at 0, add each number
System.out.println(sum);
// for sums, the built-in is simpler and avoids boxing
System.out.println(numbers.stream().mapToInt(Integer::intValue).sum());
String longest = List.of("java", "kotlin", "go").stream()
.reduce("", (a, b) -> b.length() > a.length() ? b : a);
System.out.println(longest);
}
}
// Output:
// 108
// 108
// kotlin
Finished this page? Track your progress (saved only in your browser).