To sum the elements of an ArrayList
in Java, you can use a loop to iterate through the list and add each element to a running total, or you can use the stream()
method and the reduce()
method to perform the sum in a single statement.
Here's an example using a loop:
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); int sum = 0; for (int num : numbers) { sum += num; } System.out.println(sum); // Output: 15
And here's an example using stream()
and reduce()
:
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); int sum = numbers.stream().reduce(0, Integer::sum); System.out.println(sum); // Output: 15
Both of these examples will calculate the sum of the elements in the numbers
list and print the result to the console.