Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max/Min of three or more Integers if null values are allowed

Tags:

java

java-8

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);
    }
}
like image 282
noob555 Avatar asked Sep 02 '25 10:09

noob555


1 Answers

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());
}
like image 83
Bohemian Avatar answered Sep 03 '25 23:09

Bohemian