java - Sum of elements of an Integer ArrayList without looping -


i have gone through few web resources , links, however, unable find sum of elements of integer arraylist without looping. looking function allow me in single line.

i able find same normal array follows

import java.util.arraylist; import java.util.stream.intstream;  public class sumarray {     public static void main(string[] args)     {         int[] = {10,20,30,40,50};         int sum = intstream.of(a).sum();         system.out.println("the sum " + sum);     } } 

i can write user-defined function 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 : al)         {             value += i;         }         return value;     } } 

however, i'm looking in-built. please advise.

edit : have tried following 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 resolved variable     syntax error on tokens, delete these tokens 

you can map stream<integer> intstream , calculate sum :

a1.stream().maptoint(integer::intvalue).sum(); 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -