Posts

Showing posts with the label sum a List of integers

How to sum a List of integers using Java 8 Stream

In this section, we will show you how to  sum a List of integers using Java 8 Stream. Following ways can be used to sum a List of integers: 1. By using mapToInt() method  2. By using summarizingInt() method 3. By using reduce() method Example 1: By using mapToInt () method This mapToInt () method is an intermediate operation which returns an IntStream consisting of the results of applying the given function to the elements of this stream. import java.util.ArrayList ; import java.util.Arrays ; import java.util.List ; public class Main { // Driver code public static void main ( String [] args) { //Creating List of integers List < Integer > numberList = new ArrayList< Integer >( Arrays . asList ( 5 , 2 , 3 , 4 , 9 )); //Using mapToInt int sum = numberList .stream().mapToInt( Integer ::intValue).sum(); System . out .println( "Sum of integers => " + sum ); } } Console Output: Sum of integers =