是否有可能没有循环的ArrayList的总和 [英] Is there possibility of sum of ArrayList without looping

查看:123
本文介绍了是否有可能没有循环的ArrayList的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在没有循环的情况下总计 ArrayList

Is there possibility of sum of ArrayList without looping?

PHP提供总和(数组)这将给出数组的总和。

PHP provides sum(array) which will give the sum of array.

PHP代码就像

$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

我想在Java中做同样的事情:

I wanted to do the same in Java:

List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);


推荐答案

一旦 java-8 (2014年3月)你将能够使用流

Once java-8 is out (March 2014) you'll be able to use streams:

如果您有列表<整数>

int sum = list.stream().mapToInt(Integer::intValue).sum();

如果是 int []

int sum = IntStream.of(a).sum();

这篇关于是否有可能没有循环的ArrayList的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆