Reputation: 43
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
Reputation: 11543
You can assign neededProduct
using the stream directly with one of the find* operations.
Product neededProduct = products.stream()
.filter(s -> s.getProductId().equals(id))
.findFirst()
.orElse(null);
Upvotes: 4