EN
Java - sum all ArrayList elements
3 points
In this article, we would like to show you how to sum all the elements from ArrayList in Java.
Quick solution:
xxxxxxxxxx
1
List<Integer> numbers = new ArrayList<>();
2
3
int sum = 0;
4
5
for (int number : numbers){
6
sum += number;
7
}
In this example, we add the value of each number
from numbers
ArrayList to the sum
variable.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
7
List<Integer> numbers = new ArrayList<>();
8
9
numbers.add(1);
10
numbers.add(2);
11
numbers.add(3);
12
13
int sum = 0;
14
15
for (int number : numbers){
16
sum += number;
17
}
18
19
System.out.println(sum);
20
}
21
}
Output:
xxxxxxxxxx
1
6