How to sum the elements of a List in Java

Java FAQ: How do I get the sum of a List in Java (i.e., an ArrayList or LinkedList of numeric values)?

Note: In this article I describe how to sum the elements of a List in Java. This is an interesting exercise, but in general you should use the Apache Commons libraries to calculate the sum (including ListUtils, StatUtils, MathUtils, and more). There are also new techniques in Java 8 (including Stream reduction) that I don’t know very well yet.

Source code to sum the elements of a List

There may be better ways to calculate the sum of the elements in a List in Java than this, but the following example shows the source code for a Java “sum the integers in a list” method:

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

I define a sum method like that in a MathUtils class, and call it like this to sum the contents of a List:

// create a list
List<Integer> ints = Arrays.asList(1, 2, 3);

// get the sum of the elements in the list
int sum = MathUtils.sum(ints);

I shared this sum method in a short post yesterday about how to create and populate a static List in Java, and thought I’d write a bit more about it today. As you can see, this method is written to get the sum of a list of integers, but you can use the same technique to sum double and float values as well.

Note that one thing you have to be careful with in an algorithm like this is that if you’re working with very large numbers, the sum of a list of integers may end up being a long value. (Most “sum” algorithms don’t account for this, but I thought I should mention it.)

In summary, if you needed to see how to sum the elements in a Java List, I hope that is helpful.