Home > OS >  How to convert for loop into streams?
How to convert for loop into streams?

Time:06-16

How would I use streams to achieve the same result as below? I am trying to find the average of this 'tot' value by first iterating through TickQueue (a queue implementation) and summing tot, and then afterwards dividing by the counter value to find the average.

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;

CodePudding user response:

Use a 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);

CodePudding user response:

TickQueue.stream().
filter(t -> !((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)).
forEach(t -> {
    tot  = (t.getAskPrice() - t.getBidPrice());
    counter  ;
});

You first filter out the values where ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)), and then for the remaining values calculate tot and counter.

  • Related