Aside from using loops explicitly, for List<Integer> list
you can do:
int sum = list.stream().mapToInt(Integer::intValue).sum();
If it’s an int[] arr
then do:
int sum = IntStream.of(arr).sum();
This is based on the use of streams.
Or you can do this simple one liner loop:
int sum = 0;
for (Integer e : myList) sum += e;
Even better, write a function and reuse it:
public int sum(List<Integer> list) {
int sum = 0;
for (Integer e : list) sum += e;
return sum;
}
solved How do you find the sum of all numbers in a set in Java? [duplicate]