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...!!! Click To Tweet
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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:
1 2 3 4 5 6 7 8 9 10 11 | 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...!!! Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams