[Java] How to compute average of all elements from an array?


I want to find average of all elements from an array, how can I do that in Java?

1 Answer

3 years ago by

In Java, simplest way of doing average of all elements from an array is using streams.
Following code does that

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		int[] numbers = { 22, 456, 97, 4 };
		System.out.println("Average of all numbers from the array: " + Arrays.stream(numbers).average());
	}
}

Note: the average method returns java.util.OptionalDouble. If you want a double you can do the following

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		int[] numbers = { 22, 456, 97, 4 };
		System.out.println("Average of all numbers from the array: " +  Arrays.stream(numbers).average().getAsDouble());
	}
}

This will throw exception if the array is empty. so you need to handle the following

Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.base/java.util.OptionalDouble.getAsDouble(OptionalDouble.java:130)
	at JavaArrays.main(JavaArrays.java:6)

Try online here: https://onecompiler.com/java/3xmstx7jd

3 years ago by Karthik Divi