Find the Average of Numbers in Java

We can find the average of numbers in Java in multiple ways.
Let’s say we have a list of integers. We can calculate the average with the following:

  • Using the average() operation from the Java Streams
  • Using the Java for-loop

Find the average of numbers in Java using Java Streams API

We can leverage the average() method from the IntStream class part of Java 8 Streams API to get the average number.

import java.util.*;

public class Test {

  public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    System.out.println(numbers.stream().mapToInt(Integer::intValue).average().getAsDouble());

  }
}
Output: 5.5
 
Here, we used the mapToInt(Integer::intValue) to convert the Stream<Integer> which is the result of the stream() method, to IntStream.

Calculate the average of numbers using the for-loop

Below is a program that uses Java for-loop to calculate the average of numbers.

import java.util.*;

public class Test {

  public static void main(String[] args) {
    double sum = 0;
    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    for (Integer number : numbers) {
      sum += number;
    }

    System.out.println("The average of numbers: " + sum / numbers.size());

  }
}
Output: The average of numbers: 5.5
 
In the program above, we first calculate the sum of all numbers from the list, and then we divide the sum with the number of elements to get the average number.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *