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

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...