有ArrayList不循环的和的可能性吗?
PHP提供了sum(array)将给出数组总和的函数。
PHP代码就像
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
我想在Java中做同样的事情:
List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
有ArrayList不循环的和的可能性吗?
PHP提供了sum(array)将给出数组总和的函数。
PHP代码就像
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
我想在Java中做同样的事情:
List tt = new ArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
array_sum还在内部执行一个循环,它只是向用户隐藏了它。
Answers:
然后自己写:
public int sum(List<Integer> list) {
int sum = 0;
for (int i : list)
sum = sum + i;
return sum;
}
int。在这里使用IntegerJava的自动装箱功能几乎没有价值。另外,Integer由于它是一种Immutable类型,因此每次都可能创建和重新创建许多新对象。
使用循环的唯一替代方法是使用递归。
您可以定义一个类似的方法
public static int sum(List<Integer> ints) {
return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}
与使用普通循环相比,这是非常低效的,如果列表中有很多元素,则可能会爆炸。
一种避免堆栈溢出的替代方法是使用。
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));
}
这同样效率低下,但是可以避免堆栈溢出。
写同一件事的最短方法是
int sum = 0, a[] = {2, 4, 6, 8};
for(int i: a) {
sum += i;
}
System.out.println("sum(a) = " + sum);
版画
sum(a) = 20
对我来说,最清晰的方法是:
doubleList.stream().reduce((a,b)->a+b).get();
要么
doubleList.parallelStream().reduce((a,b)->a+b).get();
它还使用内部循环,但是没有循环是不可能的。
您可以使用apache commons-collections API。
class AggregateClosure implements org.apache.commons.collections.Closure {
int total = 0;
@Override
public void execute(Object input) {
if (input != null) {
total += (Integer) input;
}
}
public int getTotal() {
return total;
}
}
然后使用如下所示的闭包:
public int aggregate(List<Integer> aList) {
AggregateClosure closure = new AggregateClosure();
org.apache.commons.collections.CollectionUtils.forAllDo(aList, closure);
return closure.getTotal();
}
如果您知道map函数,那么您知道map也可以是递归循环或递归循环。但是显然,您必须做到这一点。因此,我无法解决Java 8的问题,因为某些语法不匹配,但希望很短,所以这就是我得到的。
int sum = 0
for (Integer e : myList) sum += e;
或切换到Groovy,它在集合上具有sum()函数。[1,2,3,4,5,6] .sum()
http://groovy.codehaus.org/JN1015-收藏
在与Java类相同的JVM上运行。
Java,因此从技术上讲这不是有效的答案。
该链接显示了使用Java求和的三种不同方式,在使用Apache Commons Math的以前的答案中没有一个选项。
例:
public static void main(String args []){
List<Double> NUMBERS_FOR_SUM = new ArrayList<Double>(){
{
add(5D);
add(3.2D);
add(7D);
}
};
double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
.toArray(new Double[NUMBERS_FOR_SUM.size()]));
System.out.println(StatUtils.sum(arrayToSume));
}
请参阅StatUtils API
ArrayList不含“可累加”的东西怎么办?ArrayList和数组不一定是同一件事。至于对数组中的数字求和,这对于循环遍历元素和计算累积和非常简单。