HelloWorld HelloWorld - 1 year ago 55
Java Question

throw a exception through lambda expression

I need to throw a exception inside lambada and I'm not sure how to do it

while here is my code so far

.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.filter(product -> product == null) //like if(product==null) throw exception

I have no idea how to do that, is there any way to do this or i just by pass it by applying filter so that filter will not forward null value like
(even a hint will be usefull :))

Edit The actuall question is I need a product and if it is null then it will throw exception otherwise it will pass,it's not mentioned in question

and the code I am trying to refactor is

for(Product product : listOfProducts) {
if(product!=null && product.getProductId()!=null &&
productById = product;
if(productById == null){
throw new IllegalArgumentException("No products found with the
product id: "+ productId);

and I have other possible solution as

public Product getProductById(String productId) {
Product productById = listOfProducts.stream()
.filter(product -> product.getProductId().equalsIgnoreCase(productId)).findFirst().get();

if (productById == null)
throw new IllegalArgumentException("product with id " + productId + " not found!");

return productById;

But I want to solve it using functional interface and It'll be good that i can archive this using one line in this method like

return stream...get();

and If I need to declare a custom method to declare exception, won't be an issue

any help is appreciated


Answer Source

findFirst() returns an Optional so if you want to have your code throw an exception in case you didn't find anything, you should use orElseThrow to throw it.

.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.orElseThrow(() -> new IllegalArgumentException("No products found with the  product id: "+ productId));