szlik31
szlik31

Reputation: 43

java 8 streams loop

I'm having fun with java 8 and I have loop look like this:

    Product neededProduct = null;


    for (Iterator<Product> iterator = products.iterator(); iterator.hasNext();) {
        Product product = iterator.next();

        if (product.getProductId().equals(id)) {
            neededProduct = product;
            break;
        }
    }

and now my idea replace it with using stream,

products.stream().filter(s -> s.getProductId().equals(id)).forEach(product -> {
            neededProduct = product;
            break;
        });

but neededProduct must be final to can be used into lambda expression, break cannot be used into lambda as well, any ideas to solve this problems ?

Upvotes: 1

Views: 58

Answers (1)

Roger Lindsj&#246;
Roger Lindsj&#246;

Reputation: 11543

You can assign neededProductusing the stream directly with one of the find* operations.

Product neededProduct = products.stream()
    .filter(s -> s.getProductId().equals(id))
    .findFirst()
    .orElse(null);

Upvotes: 4

Related Questions