HelloWorld HelloWorld - 2 months ago 16
Java Question

Throw an exception if a Stream has no result

I need to throw an exception inside lambda and I'm not sure how to do it.

Here is my code so far:

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


I have no idea how to do that. Is there any way to do this or I just bypass it by applying filter so that filter will not forward null value like
filter(product->product!=null)
(even a hint will be useful :))

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 Java 8 Lambda function that throws exception?

The code I am trying to refactor is

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


I have another 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 will be good if I can achieve this using one line in this method like

...getProductById()
return stream...get();


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

Answer

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.

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