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
Related Articles:
- Java 8 – Find Largest number in an Arrays or List or Stream
- Java 8 – Find Smallest number in an Arrays or List or Stream
- Java 8 – Find 2nd Largest number in an Arrays or List or Stream
- Java 8 – Find 2nd Smallest number in an Arrays or List or Stream
- Java 8 – Find sum of Largest 2 numbers in an Arrays or List or Stream
- Java 8 – Find sum of Smallest 2 numbers in an Arrays or List or Stream
- Java 8 – Find 1st and Last elements in an Arrays
- Java 8 – Find 1st and Last elements in a List or ArrayList
- Java 8 – Find 1st and Last elements in a Set or HashSet
- Java 8 – Find 1st and Last entries in a Map or HashMap
- Java 8 – Find sum and average of a List or ArrayList
- Java 8 – How to calculate sum and average of an Arrays ?
References:
Happy Coding !!
Happy Learning !!