Multiple null checks in Java 8

  • A+
Category:Languages

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 ?

 


You may do it like so:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: