Is there possibility of sum of ArrayList
without looping?
PHP provides sum(array)
which will give the sum of array.
The PHP code is like
$a = array(2, 4, 6, 8); echo "sum(a) = " . array_sum($a) . "\n";
I wanted to do the same in Java:
List tt = new ArrayList(); tt.add(1); tt.add(2); tt.add(3);
Once java-8 is out (March 2014) you'll be able to use streams:
If you have a List<Integer>
int sum = list.stream().mapToInt(Integer::intValue).sum();
If it's an int[]
int sum = IntStream.of(a).sum();
Then write it yourself:
public int sum(List<Integer> list) { int sum = 0; for (int i : list) sum = sum + i; return sum; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With