0

I need to throw an exception if array contains a negative number.

What is best practices to do that using java8 features ?

Integer array = {11, -10, -20, -30, 10, 20, 30};

array.stream().filter(i -> i < 0) // then throw an exception
2
  • 5
    you should not throw an exception in a stream processing, that's an anti-pattern Commented Dec 27, 2020 at 14:43
  • @GovindaSakhare Thanks for the information. Have you got a source for that or a place to read more, please? Commented Dec 27, 2020 at 16:35

1 Answer 1

3

You can use use Stream::anyMatch which return a boolean then if true thrown an exception like this:

boolean containsNegativeNumber = array.stream().anyMatch(i -> i < 0);
if (containsNegativeNumber) {
    throw new IllegalArgumentException("List contains negative numbers.");
}

Or directly as this:

if (array.stream().anyMatch(i -> i < 0)) {
    throw new IllegalArgumentException("List contains negative numbers.");
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think the second approach is great because you don't use any variable to throw the exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.