java stream异常,java – 如果Stream没有结果,则抛出异常

博客讨论了如何在Java 8的Lambda表达式中抛出异常。作者遇到的问题是在流操作中检查null值并抛出异常。他们分享了两种不同的方法:一种是通过多个filter操作来避免null值,另一种是使用findFirst().orElseThrow()。作者寻求一个更简洁的解决方案,可能是通过功能接口实现。
摘要由CSDN通过智能技术生成

我需要在lambda中抛出异常,我不知道该怎么做.

到目前为止,这是我的代码:

listOfProducts

.stream()

.filter(product -> product.getProductId().equalsIgnoreCase(productId))

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

.findFirst()

.get()

我不知道该怎么做.有没有办法做到这一点,或者我只是通过应用过滤器绕过它,以便过滤器不会转发null值

filter(product-> product!= null)(即使提示也很有用:))

编辑实际问题是我需要一个产品,如果它是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();

如果我需要声明一个自定义方法来声明异常,那么这不是问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值