【发布时间】:2017-01-12 18:06:24
【问题描述】:
我需要在 lambda 中抛出一个异常,但我不知道该怎么做。
到目前为止,这是我的代码:
listOfProducts
.stream()
.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.filter(product -> product == null) //like if(product==null) throw exception
.findFirst()
.get()
我不知道该怎么做。有什么办法可以做到这一点,或者我只是通过应用过滤器来绕过它,这样过滤器就不会像这样转发空值
filter(product->product!=null)(即使是提示也会很有用:))
编辑实际的问题是我需要一个产品,如果它为空,那么它会抛出异常,否则它会通过,Java 8 Lambda function that throws exception? 中没有提到
我要重构的代码是
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);
}
我有另一个可能的解决方案
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;
}
但是我想用函数式接口来解决它,如果我能用这种方法中的一行来实现就好了
...getProductById()
return stream...get();
如果我需要声明一个自定义方法来声明异常,那将不是问题
【问题讨论】:
-
好吧,您是否需要实际的异常,这意味着您希望在有一个带有 null
product的产品时收到警报,或者您想忽略具有该值的产品? -
实际上
filter(product->product!=null)不允许空值通过,因此可能导致崩溃,因此是的,我希望得到通知 -
如果可能,您应该在
Optional上使用ifPresent而不是get,或者您可以使用orElseThrow
标签: java exception lambda java-8 java-stream