How to calculate the sum of a List in Java and Scala

As a quick note about a difference between Java and Scala, I recently wrote this blog post about How to Sum the Elements of a List in Java (ArrayList, LinkedList, etc.). For several years I have known that in Scala you sum the contents of a List like this:

// create a List
val nums = List(1,2,3)

// get the sum of the List
val total = nums.sum

So it was a real surprise that as I was working on a Java/Android app, I had to write this much code to get the sum of a Java List:

public static int sum (List<Integer> list) {
    int sum = 0;
    for (int i: list) {
        sum += i;
    }
    return sum;
}

I haven’t worked with Java since I discovered Scala, so when I got back to using Java this was a big surprise.

As I note in my other blog post, in production Java code I recommend using the Apache Commons libraries to calculate the sum of a List, or possibly the new Java 8 stream reduction techniques, which I don’t know well yet.