Q:

Multiple null checks in Java 8

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 ?

A:

You may do it like so:
String s = Stream.of(str1, str2, str3)
    .filter(Objects::nonNull)
    .findFirst()
    .orElse(str4);

A:

How about ternary conditional operator?
String s = 
    str1 != null ? str1 : 
    str2 != null ? str2 : 
    str3 != null ? str3 : str4
;

A:

You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
    s = str;
    if(s != null) break;
}

