Skip to main content

How to sum a list of integers with java 8 streams?

how to sum a list of integers with java 8 streams

Stream class not directly provide any method for sum a list of integers. So the question is how to perform sum operation. The answer is by using IntStream class that provide sum() method.
But the again question arise, how to get IntStream object from Stream object. The answer is by using mapToInt() method.


Example

SumListOfIntegers.java

package in.tecmentor;

import java.util.Arrays;
import java.util.List;

public class SumListOfIntegers {

	public static void main(String[] args) {
		List<Integer> integers = Arrays.asList(1, 2, 3, 4);
		int total = integers.stream().mapToInt(i -> i).sum();
		System.out.println("Total: " + total);
	}
}

Output:

Total: 10

Download source code

Download it- java-8-interview.zip

Leave a Reply

Your email address will not be published. Required fields are marked *

Top