Using the reduce Method
The reduce method, as its name implies, will reduce a stream to a single value and returns it as Optional. There are three overloaded reduce methods. We will demonstrate two of these methods here.
The following example uses a BinaryOperator to perform the reduction. A stream is created from a list of integers. The reduce method reduces two arguments to their sum. This operation is applied consecutively to each element of the stream. The return value is an Optional. Its get method is used to return the effective sum of the elements of the stream.
Listlist = Arrays.asList(1, 2, 3, 4);
Optionalresult = list.stream().
reduce((n1, n2) -> n1 + n2);
The output of this sequence will be a 10.
The next example illustrates the same technique applied to strings. The effect is to
concatenate the elements together separated by a dash.
Optionalname = nameList.stream().
reduce((n1, n2) -> n1 +
The output of this example follows:
The following reduce method performs a similar summation operation but is based on an initial accumulator value as the first argument of the method. The second argument is a BinaryOperator that is applied to the elements of the stream. The effect of this example is to compute the product of the elements.
ListproductList = Arrays.asList(1, 2, 3, 4);
Integer productResult = productList.
stream().reduce(1, (n1, n2) -> n1 * n2); System.out.println(productResult); Its output will be 24.