How to Find the Mean/Average of a List of Numbers in Java


The challenge

Find the mean (average) of a list of numbers in an array.

To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.

For an example list of 1, 3, 5, 7

1. Add all of the numbers

1+3+5+7 = 16

2. Divide by the number of values in the list. In this example there are 4 numbers in the list.

16/4 = 4

3. The mean (or average) of this list is 4

Test cases

import static org.junit.Assert.*;
import org.junit.Test;

public class AveragerTest {
  @Test
  public void test1() {
    assertEquals(1,
    Averager.findAverage(new int[]{1}));
  }
  @Test
  public void test2() {
    assertEquals(4,
    Averager.findAverage(new int[]{1,3,5,7}));
  }
}

Find the Mean/Average in Java

Avoid performing a for loop, in favour of an Arrays.stream:

import java.util.*;

public class Averager {
  public static int findAverage(int[] nums) {
    // sum all the elements and divide by the amount of elements
    return Arrays.stream(nums).sum()/nums.length;
  }
}

Alternatively, use the average functional directly and avoid summing and dividing by the length:

import java.util.Arrays;

public class Averager {
  public static int findAverage(int[] nums) {
    // or use the internal `average`
    return (int)Arrays.stream(nums).average().orElse(0);
  }
}

Another great option is to use the summaryStatistics extension of the InStream class to then in turn use the getAverage method as follows:

import java.util.stream.IntStream;

public class Averager {
  public static int findAverage(int[] nums) {
    // or explore the `summaryStatistics` route
    return (int)IntStream.of(nums).summaryStatistics().getAverage();
  }
}

If all else fails, there’s always good old faithful, using a for loop:

public class Averager {
  public static int findAverage(int[] nums) {
    int sum = 0;
    for (int num : nums) {
      sum += num;
    }
    return sum / nums.length;
  }
}