Hey guys in this post we will discuss about reduce()
of Stream API which is introduced in Java 8.
Table of Contents
Introduction
- Many times we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, minus, product, divide etc. Reducing is the repeated process of combining all elements
sum()
,min()
,max()
,count()
, etc are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.Stream.reduce()
is terminal method
Different variant of reduce() method
- reduce(BinaryOperator accumulator)
- reduce(T indentity, BinaryOperator accumulator)
- reduce(U indentity, BiFunction accumulator, BinaryOperator combiner)
reduce(BinaryOperator accumulator)
- It performs a reduction on the elements of the given stream, using given accumulation function
- accumulator – accumulator is a function for combining two values
#1 reduce()
method with accumulator
import java.util.Arrays;
import java.util.stream.Stream;
public class Example2 {
public static void main(String[] args) {
int numbers[] = {1,2,3,4,5};
String[] list = {"HP", "Lenovo", "Dell", "Macbook", "Acer"};
Arrays.stream(numbers)
.reduce((a, b)->a+b).ifPresent(System.out::println);
Stream.of(10,20,30,40)
.reduce(Integer::max)
.ifPresent(System.out::println);
Arrays.stream(list)
.reduce((a, b) -> a+ " | "+b)
.ifPresent(System.out::println);
}
}
//15
//40
// HP | Lenovo | Dell | Macbook | Acer
reduce(T indentity, BinaryOperator accumulator)
- indentity – the indentity value for the accumulating function
- accumulator – accumulator is a function for combining two values
#2 Reduce()
with identity and accumulator
import java.util.Arrays;
import java.util.stream.Stream;
public class Example2 {
public static void main(String[] args) {
Integer numbers[] = {1,2,3,4,5};
String[] list = {"HP", "Lenovo", "Dell", "Macbook", "Acer"};
Integer resultOne = Stream.of(numbers)
.reduce(100, (x, y)-> x+y);
System.out.println(resultOne);
Integer resultTwo = Arrays.stream(numbers)
.reduce(100, Integer::max);
System.out.println(resultTwo);
String resultThree = Stream.of(list)
.reduce("Programming languages:", (x, y)->x+" | "+y);
System.out.println(resultThree);
}
}
Reduce(U indentity, BiFunction accumulator, BinaryOperator combiner)
- identity – the identity value for the combiner function
- accumulator – accumulator is function for incorporating additional element into result
- combiner – combiner is function for combining two values. combiner works with only parallelStream