Side Navigation

X

Average Value

Write a method that returns the average of a list of integers.

Average = Total Sum of All Numbers / Number of Item in the Set

 

public class BestOnlineLearning {

    public static double maxNumber(int[] list){
        int sum = 0;
        double avg = 0.0;
        for(int i = 0; i< list.length; i++){
            sum = sum + list[i];
        }
        System.out.println(sum / list.length);
        return avg = sum/list.length;
    }

    public static void main(String[] args) {
        int[] n = {100, 10};
        maxNumber(n);
    }
}

using java 1.8 lambdas

public static double maxNumber(int[] list){
   return Arrays.stream(list)
                .mapToDouble(i -> i)
                .average()
                .getAsDouble();
}

streams implementation for ArrayList

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

        return list.stream()
                .mapToInt(i -> i)
                .average()
                .getAsDouble();

 

You May Also Like

Comments

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>