我想知道是否有比我正在尝试的更好、更短、更优雅的方法来实现这一目标。假设我有 3 个整数(value1、value2、value3),我想找到这些整数中的最大值,并且它们允许为空值。我无法使用下面的代码,因为它可能会抛出 NullPointerException:
Math.max(Math.max(value1, value2), value3)
Run Code Online (Sandbox Code Playgroud)
我写了一个野蛮的代码(如下所示),但它不会缩放超过 3 个整数:
public Integer getMaxValue(Integer value1, Integer value2, Integer value3) {
Integer defaultValue = 1;
if (value1 == null && value2 == null && value3 == null) {
return defaultValue;
} else if (value1 == null && value2 != null && value3 != null) {
return Math.max(value2, value3);
} else if (value2 == null && value1 != null && value3 != null) {
return Math.max(value1, value3);
} else if (value3 == null && value1 != null && value2 != null) {
return Math.max(value1, value2);
} else if (value1 == null && value2 == null) {
return value3;
} else if (value2 == null && value3 == null) {
return value1;
} else if (value1 == null && value3 == null) {
return value2;
} else {
return Math.max(Math.max(value1, value2), value3);
}
}
Run Code Online (Sandbox Code Playgroud)
怎么样
public Integer getMaxValue(Integer... numbers) {
return Arrays.stream(numbers)
.filter(Objects::nonNull)
.max(naturalOrder())
.orElse(1);
}
Run Code Online (Sandbox Code Playgroud)
这可以处理任意数量的整数,其中任何一个或全部都可以为空。
Optional<T>您可以将其转换为返回而不是的通用方法,T因为T.
public <T extends Comparable<? super T>> Optional<T> getMaxValue(T... numbers) {
return Arrays.stream(numbers)
.filter(Objects::nonNull)
.max(naturalOrder());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1129 次 |
| 最近记录: |