1

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

how can I fix it?

Naman
  • 27,789
  • 26
  • 218
  • 353
TuGordoBello
  • 4,350
  • 9
  • 52
  • 78
  • 3
    Your code uses `orElseThrow`, which throws if the Optional is *absent*, i.e. if you didn't find any element. Use ifPresent(). Or use an if block with anyMatch. And don't compare objects with `==`. Use equals() in general, and use compareTo with BigDecimal. – JB Nizet Dec 13 '19 at 16:15
  • If I can add one thing to improve your code then I would advise you do not use exceptions to control your code. – kolboc Dec 13 '19 at 16:16
  • Also note that BigDecimal.ZERO exists. – JB Nizet Dec 13 '19 at 16:17

1 Answers1

3

You can use anyMatch to perform an if check and throw the exception as:

if(myList.stream().anyMatch(d -> d.getNetPrice().equals(BigDecimal.ZERO)) {
    throw new DocumentRequestException("The product has 0 'NetPrice' as a value")
}
Naman
  • 27,789
  • 26
  • 218
  • 353