Java 8 Stream- Sum of List of Integers


Java 8 Stream interface provides mapToInt() method to convert a stream integers into a IntStream object and upon calling sum() method of IntStream, we can calculate the sum of a list of integers.

IntStream is available for primitive int-valued elements supporting sequential and parallel aggregate operations.

int total1 = listOfInteger.stream().mapToInt(Integer::intValue).sum();
int total2 = listOfInteger.stream().mapToInt(i -> i).sum();
// Bonus point :)
int total3 = listOfInteger.stream().collect(Collectors.summingInt(Integer::intValue));

Let’s see the full example.

Main.java
package org.websparrow;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

	public static void main(String[] args) {

		List<Integer> listOfInteger = Arrays.asList(8, 22, 02, 28);

		// Java 8- method reference
		int total1 = listOfInteger.stream().mapToInt(Integer::intValue).sum();
		System.out.println("Total 1:" + total1);

		// Java 8- traditional way
		int total2 = listOfInteger.stream().mapToInt(i -> i).sum();
		System.out.println("Total 2:" + total2);

		// Java 8- Collectors: Bonus point:)
		int total3 = listOfInteger.stream()
				.collect(Collectors.summingInt(Integer::intValue));
		System.out.println("Total 3:" + total3);
	}
}

Output

Total 1:60
Total 2:60
Total 3:60

References

  1. Interface Stream
  2. Interface IntStream
  3. Class Collectors

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.