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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

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 last