There are three types of reduce methods.
Try this code to understand it better
/**
* T reduce(T identity, BinaryOperator<T> accumulator)
*
* identity = initial value
* accumulator = first process initial value to first element of the stream,
* then process the result with the next element in the stream
*/
String name = Stream.of("T", "O", "M", "M", "Y")
.reduce("", (a,n) -> a + n);
System.out.println(name);
int sum = Stream.of(1,2,3,4,5,6,7,8,9,10)
.reduce(0, (a,n) -> a + n);
System.out.println(sum);
int multi = Stream.of(1,2,3,4,5,6,7,8,9,10)
.reduce(1, (a,n) -> a * n);
System.out.println(multi);
/**
* Optional<T> reduce(BinaryOperator<T> accumulator)
*
*/
Optional<String> optName = Stream.of("T", "O", "M", "M", "Y")
.reduce((a,n) -> a + n);
if(optName.isPresent()){
System.out.println(" get from optional --> " + optName.get());
}
/**
* <U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
*
* This method signature is used when we are dealing with different types.
* It allows Java to create intermediate reductions and then combine them at the end.
*/
int total = Stream.of("R", "a", "z", "v", "a", "n")
.reduce(0, (a,b) -> a + b.length(), (x,y) -> x + y);
// 0 = initial value type int
// a = int, must match the identity type
// b.method() return type must match the a and the identity type
// x,y from BinaryOperator
System.out.println(total);
String names[] = {"Bobby", "Mark", "Anthony", "Danna"};
int sumAll = Stream.of(names)
.reduce(0, (a,b) -> a + b.length(), (x,y) -> x + y);
System.out.println(sumAll);
String csvNames = Stream.of(names)
.reduce("", (a,b) -> a + b + ";");
System.out.println(csvNames);
reduce: it will tell you what types a and b are, and what they represent exactly.long total = catalog.stream().mapToLong(a -> a.getUnitPrice() * a.getUnitsInStore()).sum()