Is there possibility of sum of ArrayList
without looping?
PHP provides sum(array)
which will give the sum of array.
The PHP code is
If you know about the map function, then you know that a map is also can be recursive loop or recursive loop. But obviously you have to reach each element for that. so, I could not work out the Java 8, because some syntax mismatch but wanted a very short so this is what I got.
int sum = 0
for (Integer e : myList) sum += e;
You can use GNU Trove library:
TIntList tt = new TIntArrayList();
tt.add(1);
tt.add(2);
tt.add(3);
int sum = tt.sum();
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;
}
You can use 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;
}
}
Then use this closure as shown below:
public int aggregate(List<Integer> aList) {
AggregateClosure closure = new AggregateClosure();
org.apache.commons.collections.CollectionUtils.forAllDo(aList, closure);
return closure.getTotal();
}
The only alternative to using a loop is to use recursion.
You can define a method like
public static int sum(List<Integer> ints) {
return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}
This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.
An alternative which avoid a stack overflow is to use.
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));
}
This is just as inefficient, but will avoid a stack overflow.
The shortest way to write the same thing is
int sum = 0, a[] = {2, 4, 6, 8};
for(int i: a) {
sum += i;
}
System.out.println("sum(a) = " + sum);
prints
sum(a) = 20