

Here is java 8 stream reduce example like sum of integers using reduce() method of stream, Join stream using reduce method of stream.
Table of Contents
Example 1: Stream reduce
java.util.List<Integer> integer = Arrays.asList(1, 2, 15, 10, 5, 5, 10, 3, 4); int total = integer.stream().reduce((integer1, integer2) -> { return integer1 + integer2; }).get(); System.out.print("Sum of number is : " + total);
Output:
Sum of number is : 55
Example 2: Stream reduce with seed value
java.util.List<Integer> integer = Arrays.asList(1, 2, 15, 10, 5, 5, 10, 3, 4); int total = integer.stream().reduce(0, (sum, i) -> { sum = sum + i; return sum; }); System.out.print("Sum of number is : " + total);
output:
Sum of number is : 55
Example 3: Join List of String
java.util.List<String> strings = Arrays.asList("Zohne", "Redy", "Zohne", "Redy", "Stome"); String joinString = strings.stream().reduce((string1, string2) -> { return string1 + ", " + string2; }).get(); System.out.println("Join String using reduce: "+joinString);
Output:
Join String using reduce: Zohne, Redy, Zohne, Redy, Stome
References:
https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.