我需要在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));