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:
108The 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.0With 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.0Common 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
4000000000Functions used in this recipe
- Arrays.stream() — Creates a stream from an array — for sums, filters and transformations.
- IntStream.sum() — Adds up all numbers of a stream.
- IntStream.average() — Computes the arithmetic mean of the numbers in a stream.