更新时间:2022-01-30 22:17:22
除了显式使用循环之外,对于 List
你可以做的:
Aside from using loops explicitly, for List<Integer> list
you can do:
int sum = list.stream().mapToInt(Integer::intValue).sum();
如果它是一个 int[] ar
然后做:
If it's an int[] ar
then do:
int sum = IntStream.of(ar).sum();
这是基于流的使用.
或者你可以做这个简单的单线循环:
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;
}