Home  >  JDK 8

Java 8 Sum: Array, Map and List Collection Example using reduce() and collect() Method

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

Sum 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.

Sum 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.

Sum 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
package com.concretepage;
public class Line {
	private int length;
	public Line(int length) {
		this.length = length;
	}
        public int getLength() {
		return length;
	}
} 

Sum using Stream.reduce() 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.

Sum using Stream.reduce() with 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); 

Sum of Array Example


SumOfArrayDemo.java
package com.concretepage;
import java.util.Arrays;
import java.util.function.IntBinaryOperator;
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 

Sum of List Example


SumOfListDemo.java
package com.concretepage;
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
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 

Sum of List of Array Example


SumOfListOfArrayDemo.java
package com.concretepage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
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 

Sum of Map Example


SumOfMapValues.java
package com.concretepage;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.Map;
import java.util.stream.Collectors;
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
FIND MORE TUTORILAS
comments powered by Disqus


Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us