Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Closed
5 years ago
.
The community reviewed whether to reopen this question
last year
and left it closed:
Original close reason(s) were not resolved
–
–
–
–
–
–
–
–
–
Guava
has a method that does something similar called
MoreObjects.firstNonNull(T,T)
.
Integer x = ...
int y = MoreObjects.firstNonNull(x, -1);
This is more helpful when you have something like
int y = firstNonNull(calculateNullableValue(), -1);
since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.
–
–
–
–
Short answer: no
The best you can do is to create a static utility method (so that it can be imported using import static
syntax)
public static <T> T coalesce(T one, T two)
return one != null ? one : two;
The above is equivalent to Guava's method firstNonNull
by @ColinD, but that can be extended more in general
public static <T> T coalesce(T... params)
for (T param : params)
if (param != null)
return param;
return null;
–