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 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 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."); }