1

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
6
  • one way or another some looping will be used, you can use a divide-and-conquer recursive (or iterative) approach since sums satisfy the partial sums property, i.e a sum is equal to the sum of partial sums Commented Aug 19, 2015 at 16:07
  • 7
    possible duplicate of Is there possibility of sum of ArrayList without looping Commented Aug 19, 2015 at 16:07
  • @saltandwater What errors do you get? Commented Aug 19, 2015 at 16:29
  • @kajacx, please see edit above for errors Commented Aug 19, 2015 at 16:56
  • Are you sure you are using java 8? Run java -version from command line or check java instalation folder for version. Streams (you are using those) are only avaliable in java 8. Commented Aug 19, 2015 at 17:13

2 Answers 2

1

You can easily map a Stream<Integer> to an IntStream and then calculate the sum :

a1.stream().mapToInt(Integer::intValue).sum();
Sign up to request clarification or add additional context in comments.

10 Comments

map uses loops implicitly!
@NikosM. I don't think the OP minds that. He's just looking for a built-in method.
@NikosM. You'll always have some loop behind the scenes, since you must iterate over all the elements in order to calculate the sum.
@Eran, thanks for the response. I have tried the above, but I get some build errors, please see EDIT above. Is it something related to java versioning?
@saltandwater You must have java 8.
|
1
al.stream().reduce(0, (x,y) -> x+y)

1 Comment

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.