des*_*224 -2 java collections loops java-stream
我将如何使用流来实现与下面相同的结果?我试图通过首先迭代 TickQueue (队列实现)并对 tot 求和,然后除以计数器值来找到平均值,从而找到此“tot”值的平均值。
int counter = 0;
double tot = 0;
for (Tick t: TickQueue)
{
if ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0))
{
tot += 0;
}
else
{
tot += (t.getAskPrice() - t.getBidPrice());
counter++;
}
}
double avg = tot/counter;
Run Code Online (Sandbox Code Playgroud)
使用DoubleStream
for sum/average/count
:
double avg = tickQueue.stream()
.filter(t -> t.getAskPrice() != 0 && t.getBidPrice() != 0)
.mapToDouble(t -> t.getAskPrice() - t.getBidPrice())
.average()
.orElse(0.0);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
88 次 |
最近记录: |