Find average of a list in Java


To find average of a list in Java, the code is as follows -

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String []args){
      List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500);
      IntSummaryStatistics summaryStats = list.stream()
      .mapToInt((a) -> a)
      .summaryStatistics();
      System.out.println("Average of a List = "+summaryStats.getAverage());
   }
}

Output

Average of a List = 156.66666666666666

Let us now see another example -

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String []args){
      List<Integer> list = Arrays.asList(10, 20, 50, 100, 130, 150, 200, 250, 500);
      int sum = 0;
      for (int i : list) {
         sum+=i;
      }
      if(list.isEmpty()){
         System.out.println("Empty list!");
      } else {
         System.out.println("Average = " + sum/(float)list.size());
      }
   }
}

Output

Average = 156.66667

Updated on: 02-Jan-2020

669 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements