How to convert a possible null-value to a default value using Guava?

Chriss picture Chriss · Nov 7, 2011 · Viewed 60.5k times · Source

Does Guava provide a method to get a default value if a passed object reference is null ? I'am looking for something like <T> T nullToDefault(T obj, T default), were the default is returned if obj is null.

Here on stackoverflow I found nothing about it. I am only looking for a pure Guava solution (if there is some)!

I found nothing in the Gauva 10 API, only com.google.common.base.Objects looks promising but lacks something similar.

Answer

ColinD picture ColinD · Nov 7, 2011

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);