Java 8流中的IfPresentOrElse场景

问题描述

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

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

在这里,我试图根据productnames进行过滤,该方法工作得很好,但是我需要在anymatch中添加else条件。如果找不到匹配项,我需要抛出一个错误找不到产品”。我尝试使用ifPresentOrElse,但是它使用Consumer接口作为返回void的参数(但在我的情况下,它必须返回布尔值)。任何帮助表示赞赏。@H_404_1@

谢谢。@H_404_1@

解决方法

您可以使用orElseThrow

orElseThrow(ProductNotFoundException::new)

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

例如:

 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();
                    }
                });

为流执行添加终端操作。