public static float myAverage(List<Float> elems){
return /* Answer with no loop */;
}
如何在一行中获得List的平均值; 没有额外的库像apache,没有循环 请帮帮我
我无法制作其他方法和类。
-----原始---
//The answer must have balanced parentesis, and not containing "exerciseAverage"
import java.util.*;
public class Exercise{
public static float myAverage(List<Float> elems){[???]}
//compute the average, 0f on empty lists
public static float exerciseAverage(List<Float> elems){
/*omitted*/
/*omitted*/
/*omitted*/
}
public static void main(String [] arg){
List<List<Float>> tests=Arrays.asList(
Arrays.asList(1f,2f,3f,4f,5f,6f,7f),
Arrays.asList(-1f,-2f,-3f,-7f,-13f),
Arrays.asList(-0.5f,0f,0f,0f,30f,-100f,200f,23f,42f),
Arrays.asList(-12f/3f,32f,12f,45f,-1000f,99f),
Arrays.asList(-13f/0f,-100f/0f),
Arrays.asList(7f,6f,4f,3f,2f,1f,0f,-100f),
Arrays.asList(7f,6f,4f,3f,2f,1f,0f,1f,2f,3f,4f,5f,6f,7f,8f)
);
for(List<Float> ls:tests)
assert myAverage(ls)==exerciseAverage(ls): "error on"+ls+" "+myAverage(ls)+" " +exerciseAverage(ls);
}
}
---我找到了!
return (elems.size() == 0 ) ? 0 : (myAverage(elems.subList(0, elems.size()-1) ) * (elems.size()-1) + elems.get(elems.size()-1))/(float)elems.size();
答案 0 :(得分:6)
使用Java 8:
return elems.stream().reduce(0F, Float::sum) / elems.size();
或者
return (float) elems.stream().mapToDouble(Float::doubleValue).average().getAsDouble();
答案 1 :(得分:2)
使用递归:
public static float myAverage(List<Float> elems){
final int N = elems.size(); // For brevity, inline if you wish
return (N == 0) ? 0 : (myAverage(elems.subList(1,N)) * (N-1) + elems.get(0)) / N;
}
然而,请注意,这将遇到严重的数字问题;你不应该将它用于真正的数学工作。