Home > Blockchain >  Can I make this for loop and if statement more concise with a stream?
Can I make this for loop and if statement more concise with a stream?

Time:12-19

My code works fine but I want to get practice with Java 8 streams. I was wondering if I can use a stream for this?

quoteOrders is a list of order objects that implement IOrder. If the data is something like bookOrder the if statement will be true for that object and then return bookOrder.handleOrderRequest(data).

For(IOrder order: quoteOrders){
        if(order.hasRequest(data)){
                return order.handleOrderRequest(data);
        }
}

I thought about maybe changing it to something like but I am not sure how to add the return statement part or if it is even possible with streams.

return quoteOrders.forEach(quoteOrder -> { quoteOrders.stream().filter(order -> order.hasRequest(data))

CodePudding user response:

You could use filter to emulate the if statement, and then return the findFirst of the stream:

return quoteOrders.stream()
                  .filter(order -> order.hasRequest(data))
                  .findFirst()
                  .map(order -> order.handleOrderRequest(data))
                  .orElse(null); // or some other default behavior
  • Related