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

前端之家收集整理的这篇文章主要介绍了java – 如果Stream没有结果,则抛出异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在lambda中抛出异常,我不知道该怎么做.

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

  1. listOfProducts
  2. .stream()
  3. .filter(product -> product.getProductId().equalsIgnoreCase(productId))
  4. .filter(product -> product == null) //like if(product==null) throw exception
  5. .findFirst()
  6. .get()

我不知道该怎么做.有没有办法做到这一点,或者我只是通过应用过滤器绕过它,以便过滤器不会转发null值
filter(product-> product!= null)(即使提示也很有用:))

编辑实际问题是我需要一个产品,如果它是null,那么它将抛出异常,否则它会通过,它在Java 8 Lambda function that throws exception?中没有提到

我试图重构的代码

  1. for(Product product : listOfProducts) {
  2. if(product!=null && product.getProductId()!=null &&
  3. product.getProductId().equals(productId)){
  4. productById = product;
  5. break;
  6. }
  7. }
  8. if(productById == null){
  9. throw new IllegalArgumentException("No products found with the
  10. product id: "+ productId);
  11. }

我有另一个可能的解决方

  1. public Product getProductById(String productId) {
  2. Product productById = listOfProducts.stream()
  3. .filter(product -> product.getProductId().equalsIgnoreCase(productId)).findFirst().get();
  4.  
  5. if (productById == null)
  6. throw new IllegalArgumentException("product with id " + productId + " not found!");
  7.  
  8. return productById;
  9. }

但是我想用功能界面解决它,如果我能用这种方法中的一行来实现这一点就好了

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

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

解决方法

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

猜你在找的Java相关文章