HelloWorld HelloWorld - 1 year ago 75
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:

.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 bypass it by applying filter so that filter will not forward null value like
(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 &&
productById = product;
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

return stream...get();

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

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download