如何使用lambda表达式引发异常



如果数组包含负数,我需要抛出一个异常。

使用java8特性实现这一点的最佳实践是什么?

Integer array = {11, -10, -20, -30, 10, 20, 30};
array.stream().filter(i -> i < 0) // then throw an exception

您可以使用返回布尔值的Stream::anyMatch,如果为true,则抛出如下异常:

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

或者直接如下:

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

最新更新