[英]How to Throw exception using Stream on List when try to find element?
I want to throw an exception using stream when I find an element by condition当我按条件查找元素时,我想使用流抛出异常
myList.stream()
.filter(d -> (d.getNetPrice() != new BigDecimal(0)))
.findAny()
.orElseThrow(
() -> new DocumentRequestException("The product has 0 'NetPrice' as a value"));
for request请求
{
"sku": "123",
"quantity": 3,
"description": "pc",
"netPrice": 16806,
"amount": 50418
},
{
"sku": "1234",
"quantity": 2,
"description": "notebook",
"netPrice": 0,
"amount": 0
}
So for that example I want the exception because the list contains one element with 'netPrice' = 0 but the code return the Pc element and nothing else happend因此,对于该示例,我想要异常,因为列表包含一个带有 'netPrice' = 0 的元素,但代码返回 Pc 元素,并且没有发生其他任何事情
how can I fix it?我该如何解决?
You can use anyMatch
to perform an if
check and throw the exception as:您可以使用
anyMatch
执行if
检查并抛出异常:
if(myList.stream().anyMatch(d -> d.getNetPrice().equals(BigDecimal.ZERO)) {
throw new DocumentRequestException("The product has 0 'NetPrice' as a value")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.