有ArrayList
没有循环的总和的可能性?
PHP提供的sum(array)
将给出数组的总和.
PHP代码就像
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
Run Code Online (Sandbox Code Playgroud)
我想在Java中做同样的事情:
List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
Run Code Online (Sandbox Code Playgroud)
msa*_*yag 136
如果你有 List<Integer>
int sum = list.stream().mapToInt(Integer::intValue).sum();
Run Code Online (Sandbox Code Playgroud)
如果是的话 int[]
int sum = IntStream.of(a).sum();
Run Code Online (Sandbox Code Playgroud)
Erh*_*mir 22
然后自己写:
public int sum(List<Integer> list) {
int sum = 0;
for (int i : list)
sum = sum + i;
return sum;
}
Run Code Online (Sandbox Code Playgroud)
写一个像util这样的函数
public class ListUtil{
public static int sum(List<Integer> list){
if(list==null || list.size()<1)
return 0;
int sum = 0;
for(Integer i: list)
sum = sum+i;
return sum;
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用喜欢
int sum = ListUtil.sum(yourArrayList)
Run Code Online (Sandbox Code Playgroud)
使用循环的唯一替代方法是使用递归.
您可以定义类似的方法
public static int sum(List<Integer> ints) {
return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}
Run Code Online (Sandbox Code Playgroud)
与使用普通循环相比,这是非常低效的,如果列表中有许多元素,则可能会爆炸.
可以使用避免堆栈溢出的替代方法.
public static int sum(List<Integer> ints) {
int len = ints.size();
if (len == 0) return 0;
if (len == 1) return ints.get(0);
return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}
Run Code Online (Sandbox Code Playgroud)
这同样效率低下,但会避免堆栈溢出.
编写相同内容的最短路径是
int sum = 0, a[] = {2, 4, 6, 8};
for(int i: a) {
sum += i;
}
System.out.println("sum(a) = " + sum);
Run Code Online (Sandbox Code Playgroud)
版画
sum(a) = 20
Run Code Online (Sandbox Code Playgroud)
对我来说,最清晰的方法是:
doubleList.stream().reduce((a,b)->a+b).get();
Run Code Online (Sandbox Code Playgroud)
或者
doubleList.parallelStream().reduce((a,b)->a+b).get();
Run Code Online (Sandbox Code Playgroud)
它也使用内部循环,但不可能没有循环。
归档时间: |
|
查看次数: |
154725 次 |
最近记录: |