I am wondering if there a better, short and elegant way to achieve this than what i am trying. Let's say i have 3 Integers(value1, value2, value3) and i want to find max value out of those Integers and null values are allowed for them. I cannot use below code because it could throw NullPointerException:
Math.max(Math.max(value1, value2), value3)
I have written a barbaric code(shown below) but it won't scale for more than 3 integers:
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);
}
}
How about
public Integer getMaxValue(Integer... numbers) {
return Arrays.stream(numbers)
.filter(Objects::nonNull)
.max(naturalOrder())
.orElse(1);
}
This handles any number of Integers, any or all of which can be null.
You could convert this to a generic method that returns Optional<T>
rather than T
since there is no common default value for T
.
public <T extends Comparable<? super T>> Optional<T> getMaxValue(T... numbers) {
return Arrays.stream(numbers)
.filter(Objects::nonNull)
.max(naturalOrder());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With