Multiple null checks in Java 8

sparker picture sparker · Feb 21, 2019 · Viewed 10k times · Source

I have the below code which is bit ugly for multiple null checks.

String s = null;

if (str1 != null) {
    s = str1;
} else if (str2 != null) {
    s = str2;
} else if (str3 != null) {
    s = str3;
} else {
    s = str4;
}

So I tried using Optional.ofNullable like below, but its still difficult to understand if someone reads my code. what is the best approach to do that in Java 8.

String s = Optional.ofNullable(str1)
                   .orElse(Optional.ofNullable(str2)
                                   .orElse(Optional.ofNullable(str3)
                                                   .orElse(str4)));

In Java 9, we can use Optional.ofNullablewith OR, But in Java8 is there any other approach ?

Answer

Ravindra Ranwala picture Ravindra Ranwala · Feb 21, 2019

You may do it like so:

String s = Stream.of(str1, str2, str3)
    .filter(Objects::nonNull)
    .findFirst()
    .orElse(str4);