Skip to main content

Java 8 Reduce() Method with examples | Stream API

Java 8 Reduce Method with Examples - Java 8 Stream API
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

  1. reduce(BinaryOperator accumulator)
  2. reduce(T indentity, BinaryOperator accumulator)
  3. 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

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...