Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring object out of a for loop

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?

like image 355
Gherkin in God mode Avatar asked Nov 21 '25 20:11

Gherkin in God mode


2 Answers

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

like image 180
Deadpool Avatar answered Nov 24 '25 09:11

Deadpool


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)
like image 31
sgtcortez Avatar answered Nov 24 '25 08:11

sgtcortez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!