浮点数的 Java 8 流平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25876750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 stream average for float
提问by alexanoid
I have the following model:
我有以下模型:
public class WeightChange {
private float value;
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
}
and collection:
和收集:
private List<WeightChange> weightChanges;
I have implemented function that gets average weight value using Java 8 features:
我已经实现了使用 Java 8 功能获取平均重量值的函数:
public float getAvgChangedWeight() {
return (float) weightChanges.stream().mapToDouble(WeightChange::getValue).average().getAsDouble();
}
Could you please help improve it because I don't think that casting to double is a good idea.
您能否帮助改进它,因为我认为将其转换为 double 不是一个好主意。
Also it throws an exception when the weightChanges
collection is empty. How does one improve it in this case?
当weightChanges
集合为空时,它也会抛出异常。在这种情况下如何改进它?
采纳答案by Misha
To answer the second part of your question, if you want to avoid the exception when the list is empty and return some double
value, use orElse
instead of getAsDouble
:
要回答问题的第二部分,如果您想在列表为空时避免异常并返回一些double
值,请使用orElse
代替getAsDouble
:
return weightChanges.stream()
.mapToDouble(WeightChange::getValue)
.average()
.orElse(Double.NaN);