reduce method of Stream class

  • reduce is an aggregating method that aggregates the output into a single value
  • stream class has 3 variant of reduce method for which return types of each is different
    • Optional reduce(BinaryOperator accumulator);
    • T reduce(T identity, BinaryOperator<T> accumulator);
    • <U> U reduce(U identity,BiFunction<U, ? super T> accumulator,BinaryOperator<U> combiner);

Example :

Example :

Example 3:

public class Example {
	public static void main(String[] args) {
		//0 is required since that method signature only returns data of that type other 1 returns optional
		Integer sum = Stream.of(1,2,3,4,5,6,7,8,9,10).reduce(0,(x,y)->x+y);
	}
}

Leave a Comment