Java 8 – How to calculate sum and average of an Arrays

In this article, we will discuss how to calculate sum and average of an Arrays in Java 8

1. Java 8 – Find sum and average of an Arrays

  • Use IntStream.sum() to find sum of an Arrays in integer type
  • Use IntStream.average() to find average of an Arrays in double type

CalculateSumAndAverageOfArraysInJava8.java

package in.bench.resources.arrays.sum.average;

import java.util.Arrays;

public class CalculateSumAndAverageOfArraysInJava8 {

	public static void main(String[] args) {

		// local variables
		int sum = 0;
		double average = 0.0;


		// actual array with values
		int[] array = new int[]{
				2, 3, 5, 7, 11, 13, 17
		};


		// calculate sum using Java 8 Stream API
		sum = Arrays.stream(array).sum();


		// print sum to the console
		System.out.println("Sum is = " + sum);


		// calculate average using Java 8 Stream API
		average = Arrays.stream(array).average().orElse(Double.NaN);


		// print sum to the console
		System.out.println("Average is = " + average);
	}
}

Output:

Sum is = 58
Average is = 8.285714285714286

2. Java – Find sum and average of an Arrays

  • Use standard for-loop to find sum of an Arrays in integer type
  • Divide calculated sum by array length to find average of an Arrays in double type

CalculateSumAndAverageOfArrays.java

package in.bench.resources.arrays.sum.average;

public class CalculateSumAndAverageOfArrays {

	public static void main(String[] args) {

		// local variables
		int sum = 0;
		double average = 0.0;


		// actual array with values
		int[] array = new int[]{
				2, 3, 5, 7, 11, 13, 17
		};


		// calculate sum
		for(int index = 0; index < array.length; index++) {
			sum = sum + array[index];
		}


		// print sum to the console
		System.out.println("Sum is = " + sum);


		// calculate average
		average = (double) sum / (double) array.length;


		// print sum to the console
		System.out.println("Average is = " + average);
	}
}

Output:

Sum is = 58
Average is = 8.285714285714286

References:

Happy Coding !!
Happy Learning !!

Java 8 - Find sum and average of a List or ArrayList
Java 8 - Sorting Arrays in Ascending and Descending order