尝试查找元素时如何使用列表上的流抛出异常?
How to Throw exception using Stream on List when try to find element?
我想在按条件查找元素时使用流抛出异常
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 的元素,但是代码 return 是 Pc 元素,没有其他发生
我该如何解决?
您可以使用 anyMatch
执行 if
检查并抛出异常:
if(myList.stream().anyMatch(d -> d.getNetPrice().equals(BigDecimal.ZERO)) {
throw new DocumentRequestException("The product has 0 'NetPrice' as a value")
}
我想在按条件查找元素时使用流抛出异常
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 的元素,但是代码 return 是 Pc 元素,没有其他发生
我该如何解决?
您可以使用 anyMatch
执行 if
检查并抛出异常:
if(myList.stream().anyMatch(d -> d.getNetPrice().equals(BigDecimal.ZERO)) {
throw new DocumentRequestException("The product has 0 'NetPrice' as a value")
}