How to bring object out of a for loop

InitialisingAttributes :

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:

enter image description here

I know that I could return null at the end of the method, however is there a more elegant way to do this?

Deadpool :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4407&siteId=1