In this tutorial, we will see “How to perform sum operation on arrays, list and map objects using reduce method in Java 8”

Sum of integers in Java 8 - array, list and map using reduce method...!!! Share on X

Example

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntBinaryOperator;

public class SumOfArrayListMap_Reduce_Java8_Stream_Example {

    public static void main(String[] args) {

        sumOfArrayUsingReduce();

        sumOfListUsingReduce();

        sumOfMapUsingReduce();
    }

    private static void sumOfArrayUsingReduce() {

        int[] arrayObj = {5,44,22,11,23,82,11,91};
        int sumOfArray;

        //Reduce Method 1
        System.out.println("Array Sum: Reduce method with IntBinaryOperator");

        IntBinaryOperator intBinaryOperator = (x, y) - > x + y;
        sumOfArray = Arrays.stream(arrayObj).reduce(0, intBinaryOperator);
        System.out.println(sumOfArray);

        //Reduce Method 2
        System.out.println("\nArray Sum: Reduce method with method reference");

        sumOfArray = Arrays.stream(arrayObj).reduce(0, Integer::sum);
        System.out.println(sumOfArray);

    }


    private static void sumOfListUsingReduce() {

        List < Integer > listObj = Arrays.asList(5, 10, 33, 11, 55);
        int sumOfList;

        System.out.println("\nList Sum: Reduce method with BinaryOperator");
        sumOfList = listObj.stream().reduce(0, (x, y) - > x + y);
        System.out.println(sumOfList);
    }


    private static void sumOfMapUsingReduce() {
        Map < Integer, Integer > mapObj = new HashMap < > ();
        mapObj.put(1, 5);
        mapObj.put(2, 10);
        mapObj.put(3, 15);
        mapObj.put(4, 20);
        mapObj.put(5, 25);

        int sumOfMap;

        System.out.println("\nMap Sum: Reduce method with method reference");
        sumOfMap = mapObj.values().stream().reduce(0, Integer::sum);
        System.out.println(sumOfMap);


    }

}

 

Output:

Array Sum: Reduce method with IntBinaryOperator
289

Array Sum: Reduce method with method reference
289

List Sum: Reduce method with BinaryOperator
114

Map Sum: Reduce method with method reference
75

Sum of integers in Java 8 - array, list and map using reduce method...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts