How to get the first non-null value in Java?
Apache Commons Lang 3
ObjectUtils.firstNonNull(T...)
Java 8 Stream
Stream.of(T...).filter(Objects::nonNull).findFirst().orElse(null)
No, there isn't.
The closest you can get is:
public static <T> T coalesce(T ...items) {
for(T i : items) if(i != null) return i;
return null;
}
For efficient reasons, you can handle the common cases as follows:
public static <T> T coalesce(T a, T b) {
return a == null ? b : a;
}
public static <T> T coalesce(T a, T b, T c) {
return a != null ? a : (b != null ? b : c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
return ...
}