Fundamentals 5 min read

How to Compute an Array’s Average in Java and Groovy: For‑Loop vs Lambda

This tutorial demonstrates three ways to calculate the average of an integer array—using a classic Java for‑loop, a Java Stream Lambda expression, and Groovy’s built‑in collection methods—complete with code samples and console output.

FunTester
FunTester
FunTester
How to Compute an Array’s Average in Java and Groovy: For‑Loop vs Lambda

Average with Java for‑loop

Define an int array, iterate with a classic for loop, accumulate the sum, then compute the average as a double by multiplying the sum by 1.0 and dividing by the array length. Example code:

package com.fun.ztest.java;

import com.fun.frame.SourceCode;

public class Tdd extends SourceCode {
    public static void main(String[] args) {
        int[] array = {43, 54, 6, 2, 75, 34, 1};
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        output(sum * 1.0 / array.length);
    }
}

The program prints 30.714285714285715, the arithmetic mean of the elements.

Average with Java Stream API (Lambda)

Convert the primitive int[] to a List<Integer> using ArrayUtils.toObject (Apache Commons Lang 3). Then use stream() with Collectors.summingInt to obtain the sum, and compute the average in the same way as the loop version.

package com.fun.ztest.java;

import com.fun.frame.SourceCode;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Tdd extends SourceCode {
    public static void main(String[] args) {
        int[] array = {43, 54, 6, 2, 75, 34, 1};
        List<Integer> integers = Arrays.asList(ArrayUtils.toObject(array));
        Integer sum = integers.stream()
                              .collect(Collectors.summingInt(x -> x));
        output(sum * 1.0 / array.length);
    }
}

The output is identical: 30.714285714285715.

Average with Groovy

Groovy provides collection helpers that eliminate boilerplate. Define the numbers as a Groovy list, then call sum() and divide by size(). No explicit conversion or loop is required.

package com.fun.ztest.groovy;

import com.fun.frame.httpclient.FanLibrary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class Td extends FanLibrary {
    private static Logger logger = LoggerFactory.getLogger(Td.class);

    public static void main(String[] args) {
        def array = [43, 54, 6, 2, 75, 34, 1];
        output(array.sum() / array.size());
    }
}

Running the Groovy script prints 30.7142857143, demonstrating the same result with considerably less code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaLambdaGroovyProgramming tutorialfor loopArray average
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.