Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading