Reputation: 7845
Is there any equivalent of python's sum()
in Java?
Upvotes: 2
Views: 6060
Reputation: 11
You could consider using myList.stream().mapToDouble(elt -> elt).sum()
to sum the elements of your list.
Upvotes: 1
Reputation: 93
There is no function like sum()
in Java.
You may create a function by yourself. Something like this:
public <T> T countArray(T[] array)
{
T tSum = 0;
for (T t : array)
{
tSum += t;
}
return tSum;
}
public <T> T countCollection(Collection<T> coll)
{
T[] array = (T[])coll.ToArray(new T[0]);
return countArray(array);
}
Upvotes: 0
Reputation: 27677
You could use StatUtils.sum(double[]) from Apache Commons Math library. The advantage is that StatUtils has other useful functions and Commons Math has many other utils.
Upvotes: 0
Reputation: 234795
There's nothing built into the language. There are plenty of libraries that do things like that, though. Or write your own three-line routine. How you do it depends on how you are representing your elements (the usual suspects—for double values—being List<Double>
or double[]
).
Upvotes: 2
Reputation: 27336
No. Simply use a loop, to cycle through each element and generate a running total.
Upvotes: 1