This is the third solution to find sum of integers in an array list. This program uses the reduce() method of java streams.
import java.util.ArrayList;
import java.util.Arrays;
public class SumOfArrayElementsUsingStreams {
public static void main(String[] args) {
// Initialize the array with integer values
ArrayList<Integer> arrList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6));
int sumNums;
/*
* using reduce () -> where a is accumulator, initial value of a is 0 and b is
* the each element in the stream
*/
sumNums = arrList.stream().reduce(0, (a, b) -> a + b);
System.out.println("The sum of integers in an array list is= " + sumNums);
}
}
OUTPUT-
The sum of integers in an array list is= 21

Leave a comment