当我按条件找到元素时,我想使用流抛出异常

 myList.stream()
      .filter(d -> (d.getNetPrice() != new BigDecimal(0)))
      .findAny()
      .orElseThrow(
          () -> new DocumentRequestException("The product has 0 'NetPrice' as a value"));


要求

{
        "sku": "123",
        "quantity": 3,
        "description": "pc",
        "netPrice": 16806,
        "amount": 50418
    },
    {
        "sku": "1234",
        "quantity": 2,
        "description": "notebook",
        "netPrice": 0,
        "amount": 0
    }


因此,对于该示例,我想要一个例外,因为列表包含一个元素,其'netPrice'= 0,但是代码返回了Pc元素,并且未发生任何其他情况

我该如何解决?

最佳答案

您可以使用anyMatch执行if检查并将异常抛出为:

if(myList.stream().anyMatch(d -> d.getNetPrice().equals(BigDecimal.ZERO)) {
    throw new DocumentRequestException("The product has 0 'NetPrice' as a value")
}

09-06 10:41