Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to sum an array and find the average

Short answer

Arrays.stream(array).sum() adds up all elements:

void main() {
    int[] numbers = {4, 8, 15, 16, 23, 42};
    IO.println(Arrays.stream(numbers).sum());
}

Output:

108

The average

average() returns an OptionalDouble — an empty array has no average:

void main() {
    int[] numbers = {4, 8, 15, 16, 23, 42};
    double average = Arrays.stream(numbers).average().orElse(0);
 
    IO.println(average);
}

Output:

18.0

With a loop

The same with a for-each loop:

void main() {
    double[] prices = {9.99, 5.01, 15.0};
    double total = 0;
    for (double price : prices) {
        total += price;
    }
    IO.println(total);
}

Output:

30.0

Common mistake

The sum of many int values may not fit into an int. Calculate in long:

void main() {
    int[] big = {2_000_000_000, 2_000_000_000};
 
    IO.println(Arrays.stream(big).sum());
    IO.println(Arrays.stream(big).asLongStream().sum());
}

Output:

-294967296
4000000000

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.