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

12 java lambda exception java-8 java-stream

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

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

listOfProducts
.stream()
.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.filter(product -> product == null) //like if(product==null) throw exception
.findFirst()
.get()
Run Code Online (Sandbox Code Playgroud)

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

编辑实际问题是我需要一个产品,如果它是null然后它将抛出异常,否则它将通过,在Java 8 Lambda函数中没有提到抛出异常?

我试图重构的代码是

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);
}
Run Code Online (Sandbox Code Playgroud)

我有另一个可能的解决方案

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

...getProductById()
return stream...get();
Run Code Online (Sandbox Code Playgroud)

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

Did*_*r L 19

findFirst()返回一个Optional如果你想让你的代码抛出异常以防你没有找到任何东西,你应该用orElseThrow它来抛出它.

listOfProducts
.stream()
.filter(product -> product.getProductId().equalsIgnoreCase(productId))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No products found with the  product id: "+ productId));
Run Code Online (Sandbox Code Playgroud)

  • @HelloWorld:只是旁注,你的原始代码跳过`null`元素,只有在没有匹配(非`null`)元素的情况下才会失败,而如果遇到`null`值之前这段代码会立即失败比赛.你必须决定是否应该在`listOfProducts`中允许`null`s. (2认同)