java8 Streams Reduce Examples
the reduce
method is used to perform a reduction operation on a stream, which combines all the elements in the stream into a single value. Here’s an example of using the reduce
method in Java:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> sum = numbers.stream().reduce(Integer::sum);
In this example, the reduce
method is used to calculate the sum of all the numbers in the numbers
list. The reduce
method takes two arguments: an identity value and a binary operator. The identity value is the initial value for the reduction and the binary operator is a function that takes two arguments and returns a single value. In this case, the identity value is 0
(the initial value for the sum) and the binary operator is Integer::sum
, which is a method reference to the sum
method of the Integer
class.
You can also use the reduce
method to find the maximum or minimum value in a stream like this:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> max = numbers.stream().reduce(Integer::max);
It’s important to note that the reduce
method returns an Optional
object. The reason for this is that the reduce method may not find any element to reduce, in this case, it will return an empty Optional.
You can also use the reduce method with a specific accumulator function.
List<Person> people = new ArrayList<>();
String fullNames = people.stream().map(p -> p.getFirstName() + " " + p.getLastName())
.reduce("", (name1, name2) -> name1 + ", " + name2);
This will give you a string with all the full names of the people separated by a comma.