【问题标题】:IfPresentOrElse scenario in java 8 streamsJava 8 流中的 IfPresentOrElse 场景
【发布时间】:2020-08-12 06:31:27
【问题描述】:

我有一个使用嵌套流的场景。 PFB 代码:

    list.parallelStream()
        .filter(item -> productList.parallelStream()
            .anyMatch(product -> product.getProductName().equals(item.getProductName())
                 && item.getQuantity() <= product.getAvailableQuantity()));

在这里,我试图根据 productnames 进行过滤,它工作得非常好,但我需要在任何匹配中添加一个 else 条件。如果没有找到匹配项,我需要抛出错误“product not found”。我尝试使用ifPresentOrElse,但它需要Consumer 接口作为返回void 的参数(但在我的情况下它必须返回一个布尔值)。任何帮助表示赞赏。

谢谢。

【问题讨论】:

  • 你试过orElseThrow吗?
  • 我不能使用带有布尔值的 orElseThrow 对吗?如何将其合并到我的代码中?
  • "throw" 抛出异常类型,不能“抛出”布尔值。
  • 我的意思是 orElseThrow 与 Optional 对象一起使用,但就我而言,我该如何使用它
  • findAny(...).orElseThrow(...) 而不是 anyMatch

标签: java java-8 java-stream


【解决方案1】:

您可以使用orElseThrow

orElseThrow(ProductNotFoundException::new)

您不能将orElseThrow()anyMatch() 一起使用,因为它返回布尔值。 您可以在filter() 上使用findAny(),这将返回Optional,然后您可以在Optional 上使用orElseThrow() 引发异常。

例如:

 list.parallelStream()
        .filter(item -> productList.parallelStream()
            .anyMatch(product -> product.getProductName().equals(item.getProductName())
                 && item.getQuantity() <= product.getAvailableQuantity()))
        .findAny().orElseThrow(ProductNotFoundException::new);

编辑

OP 想要在第一个未找到的产品上抛出错误。

        list.parallelStream()
                .filter(item -> {
                    if (productList.parallelStream().anyMatch(product -> product.getProductName().equals(item.getProductName())
                                    && item.getQuantity() <= product.getAvailableQuantity())) {
                        return true;
                    } else {
                        throw new ProductNotFoundException();
                    }
                });

为要执行的流添加一个终端操作。

【讨论】:

  • 我不能使用带有布尔值的 orElseThrow 对吗?如何将其合并到我的代码中?
  • 什么意思?你只需写findAny(...).orElseThrow(...),完成。
  • 更新了我的答案,将orElseThrow 合并到 OP 的代码中
  • 更新了答案并添加了解释。
  • findAny() 返回一个产品,但可能有多个产品@Smile
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多