加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:41:32 所属栏目:Java 来源:网络整理
导读:我需要在lambda中抛出异常,我不知道该怎么做. 到目前为止,这是我的代码: listOfProducts.stream().filter(product - product.getProductId().equalsIgnoreCase(productId)).filter(product - product == null) //like if(product==null) throw exception.fi
我需要在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();

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

解决方法

findFirst()返回一个 Optional,所以如果你想让你的代码抛出异常以防你没找到任何东西,你应该使用 orElseThrow来抛出它.
listOfProducts
.stream()
.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No products found with the  product id: "+ productId));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读