Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there possibility of sum of ArrayList without looping

Tags:

java

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); 
like image 376
Tapsi Avatar asked May 11 '11 11:05

Tapsi


2 Answers

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(); 
like image 105
msayag Avatar answered Sep 23 '22 11:09

msayag


Then write it yourself:

public int sum(List<Integer> list) {      int sum = 0;        for (int i : list)          sum = sum + i;       return sum; } 
like image 40
Erhan Bagdemir Avatar answered Sep 23 '22 11:09

Erhan Bagdemir