I have the following method that should return a product object if its name attribute matches the input string.
public Product find(String nameInput){
for(Product product : this.Products){
if(product.getName().equalsIgnoreCase(nameInput)){
return product;
}
}
}
Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?
You can use stream and findFirst to return Optional with first matching Product or empty Optional
this.Products.stream()
.filter(p->p.getName().equalsIgnoreCase(nameInput))
.findFirst();
You can also use orElse methods on Optional to return default value
You could do:
public Optional<Product> find(String nameInput){
for(Product product : this.Products){
if(product.getName().equalsIgnoreCase(nameInput)){
return Optional.of(product)
}
}
return Optional.empty();
}
or, even better, replace the ForEach loop with a Stream.
then you can use with ifPresent
find("Stackoverflow").ifPresent(consumer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With