简体   繁体   English

求ArrayList元素平均值的最短形式

[英]Shortest form of getting average of an ArrayList elements

By shortest form I mean least number of lines of java codes. 最简短的形式是指最少的Java代码行数。 I would like to get average value of items of an ArrayList of integer values. 我想获取整数值ArrayList项的平均值。 For example for the ArrayList ar : 例如ArrayList ar

ArrayList<Integer> ar = new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

I am looking for something like 我正在寻找类似的东西

ar.Average()

or 要么

ar.Sum()

or 要么

Arrays.Average(ar)

PS. PS。 I know we can do it in a loop. 我知道我们可以循环进行。 Just looking for a shorter alternative; 只是在寻找更短的选择;

You could use a Math library such as Apache Commons Math. 您可以使用数学库,例如Apache Commons Math。

http://commons.apache.org/math/apidocs/index.html http://commons.apache.org/math/apidocs/index.html

Specifically a SummaryStaticics object ( http://commons.apache.org/math/apidocs/src-html/org/apache/commons/math3/stat/descriptive/SummaryStatistics.html#line.123 ). 特别是一个SummaryStaticics对象( http://commons.apache.org/math/apidocs/src-html/org/apache/commons/math3/stat/descriptive/SummaryStatistics.html#line.123 )。 Though for something like average, it probably isn't worth importing a library. 虽然对于类似平均值的东西,可能不值得导入库。

The commons math library contains a mean as well as whatever else you probably want for simple statistics. 公共数学库包含均值以及您可能想要的用于简单统计的任何其他内容。 Perhaps exactly what your looking for? 也许正是您要找的东西?

If you're already using Java 8: 如果您已经在使用Java 8:

double average = Arrays.asList(1, 2, 3, 4)
                       .stream()
                       .map(Integer::intValue)
                       .average()
                       .getAsDouble();

代码行始终是一种毫无意义的措施,但是如果这是您所关心的:

int sum=0;for(Integer i:ar)sum += i;System.out.println(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM