Sar*_*ler -2 java lambda java-8 java-stream
我想使用Streams和Lambdas.但是如何用它重写我当前的方法呢?
public double calculate() {
double result = 0.0;
if (!mediumList.isEmpty()) {
Iterator<Medium> it = mediumList.iterator();
while (it.hasNext()) {
result= result+ it.next().getAge();
}
result = result / mediumList.size();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
你可以使用IntStream.average()
return mediumList.stream()
.mapToInt(Medium::getAge) // mapToInt makes it an IntStream of the ages
.average() // get the average of the ages.
.orElse(Double.NaN); // otherwise use Double.NaN if the list is empty.
Run Code Online (Sandbox Code Playgroud)
您需要使用mapToInt它来使其成为IntSTream,以便对其进行平均或求和.如果您只是使用,map您可以获得,Stream<Integer>但这没有sum或average功能.
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |