Multiple null checks in Java 8
You may do it like so:
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
How about ternary conditional operator?
String s =
str1 != null ? str1 :
str2 != null ? str2 :
str3 != null ? str3 : str4
;
You can also use a loop:
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
Current answers are nice but you really should put that in a utility method:
public static Optional<String> firstNonNull(String... strings) {
return Arrays.stream(strings)
.filter(Objects::nonNull)
.findFirst();
}
That method has been in my Util
class for years, makes code much cleaner:
String s = firstNonNull(str1, str2, str3).orElse(str4);
You can even make it generic:
@SafeVarargs
public static <T> Optional<T> firstNonNull(T... objects) {
return Arrays.stream(objects)
.filter(Objects::nonNull)
.findFirst();
}
// Use
Student student = firstNonNull(student1, student2, student3).orElseGet(Student::new);
I use a helper function, something like
T firstNonNull<T>(T v0, T... vs) {
if(v0 != null)
return v0;
for(T x : vs) {
if (x != null)
return x;
}
return null;
}
Then this kind of code can be written as
String s = firstNonNull(str1, str2, str3, str4);