Java 8 Reduce Method with Examples - Java 8 Stream API |
What is reduce() method in Java 8?
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.
Java 8 reduce method is terminal method.
Stream.reduce() method combine elements of stream and produce single result.
There is 3 variant of reduce method
- reduce(BinaryOperator accumulator)
- reduce(T indentity, BinaryOperator accumulator)
- reduce(U indentity, BiFunction accumulator, BinaryOperator combiner)
BinaryOperator - Represents an operation upon two operands of the same type, producing a result
of the same type as the operands. This is a specialization of BiFunction for the case where the operands and the result are all of
the same type.
Lets see each method one by one
1. 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.
in following example, we sum of two numbers and get accumulator and again sum with upcoming number. like this.
1+2 = 3,
3+3 = 6,
6+4 = 10
and in another example we take each string value and combine with "|".
Example 1 :- reduce method with accumulator
public class ReduceMethod {
public static void main(String[] args) {
int numbers[] = {1,2,3,4};
String[] languages = {"Java", "Python", "Js", "C", "C++"};
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(languages)
.reduce((a, b) -> a+" | " +b)
.ifPresent(System.out::print);
}
}Output :-
10
40
Java | Python | Js | C | C++
2. reduce(T indentity, BinaryOperator accumulator)
indentity - The indentity value for the accumulating function.
accumulator - accumulator is a function for combining two values.
Example 2 :- Reduce() method with identity and accumulator
public class ReduceMethod {
public static void main(String[] args) {
Integer numbers[] = {1,2,3,4};
String[] languages = {"Java", "Python", "Js", "C", "C++"};
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(languages)
.reduce("Programming Languages:", (x,y) -> x+" | "+y);
System.out.println(resultThree);
}
}Output :-
110
100
Programming Languages: | Java | Python | Js | C | C++
3. 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.
Lets see example of this.
Example 3 :- reduce() method with indetity, accumulator and combiner
public class ReduceMethod {
public static void main(String[] args) {String result = languages.parallelStream()
.reduce(" => ", (first, second)
-> first + " @A " + second, (first, second)
-> first + " @C " + second);
System.out.println(result);}
}
Output :-
=> @A Java @C => @A Python @C => @A Js @C => @A C @C => @A C++
In above example, we are using two different accumulators and combiner. The accumulator adds one '@A' between the result and the current string and the combiner adds one '@C'.
Lets see another example with object.
Example 4 :- reduce() method with objects
//User.java
public class User {
private String name;
private Integer salary;
public User(String name, Integer salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
}SalaryCount.java
public class SalaryCount{
public static void main(String[] args) {
List<User> userList = Arrays.asList(
new User("user_1", 10000),
new User("user_2", 20000),
new User("user_3", 30000),
new User("user_4", 40000)
);
Integer totalSalary = userList.stream()
.reduce(0, (result, current) ->
result + current.getSalary(), Integer::sum);
Integer lowestSalary = userList.stream()
.map(User::getSalary)
.reduce(Integer.MAX_VALUE, (result, current) ->
result < current ? result : current);
User highestSalary = userList.stream()
.reduce((result, current) ->
result.getSalary() > current.getSalary() ? result : current)
.orElse(null);
System.out.println("Total sum of Salary : " + totalSalary);
System.out.println("Lowest Salary : " + lowestSalary);
System.out.println("Highest Salary : " + highestSalary.getName()+
" Salary : " + highestSalary.getSalary());
}
}Output :-
Total sum of Salary : 100000
Lowest Salary : 10000
Highest Salary : user_4 Salary : 40000
- totalSalary is variable that get total of all user salary. we use reduce with identity 0, accumulator to find sum of all user's salary and then combine with Integer::sum.
- lowestSalary variable store lowest salary from all users. we used map. map operation returns one of stream salary. then we use reduce to find lowest salaray. we use indetity as Integer.MAX_VALUE, accumulator is using one ternary operation to return the lowest salaray from all user.
- highestSalary variable is User object. in this reduce operation get highest salary with User object.
See other Java 8 articles :-
Comments
Post a Comment