在Java中查找列表的平均值
要在Java中查找列表的平均值,代码如下-
示例
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()); } }
输出结果
Average of a List = 156.66666666666666
现在让我们来看另一个例子-
示例
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("空列表!"); } else { System.out.println("Average = " + sum/(float)list.size()); } } }
输出结果
Average = 156.66667