How to Calculate a Running Average in Java


How can we calculate a running average in Java?

There are many scenarios during which we might need to calculate a running average.

  1. We might only have access to a single element at a time, and it makes sense to calculate the average as elements are processed.
  2. The sum of all the values to average may be too large to be represented using the chosen data type.

Let’s see how we can achieve this running average in Java.

Suppose we have a list lst that contains integers, and we want to compute the average of all the integers in this list.

List<Integer> lst = new ArrayList<>();

How to compute the running average

As we all know, calculating the average of a sequence is as simple as dividing the sum of all the elements by the number of elements.

To calculate the average at index n given the average at index n-1, we can multiply the old average by n-1, add the new number, then divide that total by n.

1. Using for loops

We can accomplish this using a simple for loop.

Here, n is the index of the current element being processed.

long runningAverage = 0;
long n = 0;
for (int num : lst) {
  runningAverage = (n * runningAverage + num) / ++n;
}

2. Using Java 8 Streams

If we plan to use streams, we can use an AtomicLong for a long variable that can be read and written atomically.

AtomicLong runningAverage = new AtomicLong();
AtomicLong n = new AtomicLong();
lst
  .stream()
  .forEach(num -> {
    runningAverage.set(
      (n.get() * runningAverage.get() + num) /
      n.incrementAndGet()
    );
  });