如果数组包含负数,我需要抛出一个异常。
使用java8特性来实现这一点的最佳实践是什么?
Integer array = {11, -10, -20, -30, 10, 20, 30};
array.stream().filter(i -> i < 0) // then throw an exception发布于 2020-12-27 22:50:42
您可以使用use Stream::anyMatch,它返回一个布尔值,如果为真,则会抛出如下异常:
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.");
}https://stackoverflow.com/questions/65466915
复制相似问题