I have gone through a few web resources and links, however, I am unable to find the sum of elements of an Integer ArrayList without looping. I am looking for a function which will allow me to do this in a single line.
I was able to find the same for a normal array as follows
import java.util.ArrayList;
import java.util.stream.IntStream;
public class sumArray
{
public static void main(String[] args)
{
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
}
}
I can write a user-defined function as follows
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(sum(al));
}
static int sum(ArrayList<Integer> al)
{
int value = 0;
for(int i : al)
{
value += i;
}
return value;
}
}
However, I'm looking for something in-built. Please advise.
EDIT : I have tried the following but I get build errors
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
System.out.println(getVersion());
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(al.stream().mapToInt(Integer::intValue).sum());
}
static double getVersion () {
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos+1);
return Double.parseDouble (version.substring (0, pos));
}
}
Errors
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Integer cannot be resolved to a variable
Syntax error on tokens, delete these tokens