Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a method that takes in a List of Integer, Float, Double and calculate the average?

I am trying to write a method that takes in a list of numeric values – eg List<Integer>, List<Float>, List<Double> etc – and give me the average.

public double getAverage(List<? extends Number> stats) {
    double sum = 0.00;
    if(!stats.isEmpty()) {
        // sum = stats.stream()
        //            .reduce(0, (a, b) -> a + b);
        // return sum / stats.size();
    }
}

These are the errors I get:

Operator '+' cannot be applied to 'capture<? extends java.lang.Number>', 'capture<? extends java.lang.Number>'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

public double getAverage(List<? extends Number> stats) {
    return stats.stream()
      .mapToDouble(Number::doubleValue)
      .summaryStatistics()
      .getAverage();
}

or

public double getAverage(List<? extends Number> stats) {
    return stats.stream()
      .mapToDouble(Number::doubleValue)
      .average()
      .orElse(0);
}

depending on which style you prefer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading