Java Sum: Array, Map and List Collection Example

By Arvind Rai, December 13, 2023
On this page, we will provide Java 8 sum of values of Array, Map and List collection example using reduce() and collect() methods. There are various ways to calculate the sum of values in Java 8. We can use IntStream.sum(), summary statistics and can also create our own method to get the sum. We will discuss here different ways to calculate the sum.

1. Using IntStream.sum()

To get the sum of values we can use IntStream.sum() as follows for integer data type.
int sum = map.values().stream().mapToInt(i->i).sum();
int sum = list.stream().map(Line::getLength).mapToInt(Integer::intValue).sum(); 
For long data type, there is LongStream and for double data type there is DoubleStream in Java 8.

2. Using Collectors.summingInt()

1. Using Collectors.summingInt() with Stream.collect()
To get the sum of values we can use Collectors.summingInt() with Stream.collect() for integer data type.
int sum = list.stream().map(Line::getLength).collect(Collectors.summingInt(i->i)); 
For long data type, there is summingLong and for double data type there is summingDouble in Java 8.

2. Using Collectors.summarizingInt() with Stream.collect() and IntSummaryStatistics
To get the sum of values, we can use Collectors.summarizingInt() with Stream.collect() and IntSummaryStatistics.
IntSummaryStatistics stats = list.stream()
    			     .collect(Collectors.summarizingInt(Line::getLength));
IntSummaryStatistics stats = list.stream().flatMap(a->Arrays.stream(a))
			         .collect(Collectors.summarizingInt(i->i));
System.out.println(stats.getSum()); 
For long data type, we use summingLong with LongSummaryStatistics and for double data type there is summingDouble with DoubleSummaryStatistics in Java 8.
Here Line is our custom class.
Line.java
public class Line {
	private int length;
	public Line(int length) {
		this.length = length;
	}
        public int getLength() {
		return length;
	}
} 

3. With BiFunction and BinaryOperator

To get the sum of values we can use Stream.reduce() with BiFunction as accumulator and BinaryOperator as combiner in parallel processing.
int sum = list.parallelStream().reduce(0, (output, ob) -> output + ob.getLength(), (a, b) -> a + b); 
Here 0 is an identity. Identity is operated using BinaryOperator to each and every element of stream. If identity is 0, then it results into the sum of elements of stream in our example.

4. Using Custom Method

To perform addition we can also use our custom method with Stream.reduce() as follows.
int sum = Arrays.stream(array).reduce(0, StatisticsUtility::addIntData); 
Here StatisticsUtility is our custom class.
StatisticsUtility.java
package com.concretepage;
public class StatisticsUtility {
	public static int addIntData(int num1, int num2) {
		return num1 + num2;
	}
} 
We can use in-built classes for summation, too.
int sum = Arrays.stream(array).reduce(0, Integer::sum); 

5. Sum of Array

SumOfArrayDemo.java
public class SumOfArrayDemo {
    public static void main(String[] args) {
    	  int[] array = {23,43,56,97,32};
    	  System.out.println("--Using IntStream.sum()--");
    	  int sum = Arrays.stream(array).sum();
    	  System.out.println(sum);
    	  System.out.println("--Using Stream.reduce() with IntBinaryOperator--");    	  
    	  IntBinaryOperator ibop = (x,y) -> x+y;
    	  sum = Arrays.stream(array).reduce(0, ibop);
    	  System.out.println(sum);
    	  System.out.println("--Using Stream.reduce() with Integer.sum()--");
    	  sum = Arrays.stream(array).reduce(0, Integer::sum);
    	  System.out.println(sum);
    	  System.out.println("--Using custom method--");    	  
    	  sum = Arrays.stream(array).reduce(0, StatisticsUtility::addIntData);
    	  System.out.println(sum);
     }
} 
Output
--Using IntStream.sum()--
251
--Using Stream.reduce() with IntBinaryOperator--
251
--Using Stream.reduce() with Integer.sum()--
251
--Using custom method--
251 

6. Sum of List

SumOfListDemo.java
public class SumOfListDemo {
    public static void main(String[] args) {
      	  List<Line> list = new ArrayList<>();
      	  list.add(new Line(213));
      	  list.add(new Line(233));
          list.add(new Line(243));
      	  list.add(new Line(253));    	  
    	  System.out.println("--Using IntStream.sum()--");
    	  int sum = list.stream().map(Line::getLength).mapToInt(Integer::intValue).sum();
    	  System.out.println(sum);
    	  System.out.println("--Using Collectors.summingInt()--");    	  
    	  sum = list.stream().map(Line::getLength).collect(Collectors.summingInt(i->i));
    	  System.out.println(sum);    	  
    	  System.out.println("--Using summarizingInt()--");  
    	  IntSummaryStatistics stats = list.stream()
    			     .collect(Collectors.summarizingInt(Line::getLength));
    	  System.out.println(stats.getSum());
    	  System.out.println("--Using Stream.reduce() with combiner--"); 
    	  sum = list.parallelStream().reduce(0, (output, ob) -> output + ob.getLength(), (a, b) -> a + b);
    	  System.out.println(sum);
     }
}  
Output
--Using IntStream.sum()--
942
--Using Collectors.summingInt()--
942
--Using summarizingInt()--
942
--Using Stream.reduce() with combiner--
942 

7. Sum of List of Array

SumOfListOfArrayDemo.java
public class SumOfListOfArrayDemo {
	public static void main(String[] args) {
		List<Integer[]> list = new ArrayList<>();
		Integer[] a1 = {6,3,8,12};
		list.add(a1);
		Integer[] a2 = {8,13,9,22};
		list.add(a2);
  	        System.out.println("--Using Collectors.summingInt()--");		
		int sum = list.stream().flatMap(a->Arrays.stream(a)).
				           collect(Collectors.summingInt(i->i));
		System.out.println(sum);
  	        System.out.println("--Using Collectors.summarizingInt()--");			
  	        IntSummaryStatistics stats = list.stream().flatMap(a->Arrays.stream(a))
			     .collect(Collectors.summarizingInt(i->i));
  	        System.out.println(stats.getSum());
  	        System.out.println("--Using IntStream.sum()--");		
	        sum = list.stream().flatMap(a->Arrays.stream(a)).
	    		           mapToInt(Integer::intValue).sum();
		System.out.println(sum);	
	}
} 
Output
--Using Collectors.summingInt()--
81
--Using Collectors.summarizingInt()--
81
--Using IntStream.sum()--
81 

8. Sum of Map

SumOfMapValues.java
public class SumOfMapValues {
	public static void main(String[] args) {
	  Map<Integer, Integer> map = new HashMap<>();
	  map.put(1, 12);
	  map.put(2, 24);
	  map.put(3, 10);
	  System.out.println("--Using IntStream.sum()--");
  	  int sum = map.values().stream().mapToInt(i->i).sum();
  	  System.out.println(sum);
	  System.out.println("--Using BinaryOperator--");  	  
  	  sum = map.values().stream().reduce(0, Integer::sum);
  	  System.out.println(sum); 
	  System.out.println("--Using Collectors.summingInt()--");    	  
  	  sum = map.values().stream().collect(Collectors.summingInt(i->i));
  	  System.out.println(sum);
	  System.out.println("--Using Collectors.summarizingInt()--");    	  	  
          IntSummaryStatistics stats = map.values().stream().collect(Collectors.summarizingInt(i->i));
          System.out.println(stats.getSum());
	  System.out.println("--Using custom method--");         
	  sum = map.values().stream().reduce(0, StatisticsUtility::addIntData);
	  System.out.println(sum);
	}
} 
Output
--Using IntStream.sum()--
46
--Using BinaryOperator--
46
--Using Collectors.summingInt()--
46
--Using Collectors.summarizingInt()--
46
--Using custom method--
46 
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us