How to convert a possible null-value to a default value using Guava?
In additon to Objects.firstNonNull
, Guava 10.0 added the Optional class as a more general solution to this type of problem.
An Optional
is something that may or may not contain a value. There are various ways of creating an Optional
instance, but for your case the factory method Optional.fromNullable(T)
is appropriate.
Once you have an Optional
, you can use one of the or
methods to get the value the Optional
contains (if it contains a value) or some other value (if it does not).
Putting it all together, your simple example would look like:
T value = Optional.fromNullable(obj).or(defaultValue);
The extra flexibility of Optional
comes in if you want to use a Supplier
for the default value (so you don't do the calculation to get it unless necessary) or if you want to chain multiple optional values together to get the first value that is present, for example:
T value = someOptional.or(someOtherOptional).or(someDefault);
How about
MoreObjects.firstNonNull(obj, default)
See the JavaDoc.
(Historical note: the MoreObjects
class used to be called Objects
, but it got renamed to avoid confusion with the java.util.Objects
class introduced in Java 7. The Guava Objects
class is now effectively deprecated.)
As said previously, the Guava solution is correct.
There is however a pure JDK solution with Java 8 :
Optional.ofNullable( var ).orElse( defaultValue );
See documentation of java.util.Optional
This should do the trick: Objects.firstNonNull(o, default)
See guava API doc