Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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.

like image 691
Chriss Avatar asked Nov 07 '11 16:11

Chriss


People also ask

Can null be a default value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

Which has a default value of NULL Java?

Reference Variable value: Any reference variable in Java has a default value null.

What do you understand by default value and null value?

null means that some column is empty/has no value, while default value gives a column some value when we don't set it directly in query.


2 Answers

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); 
like image 137
ColinD Avatar answered Sep 23 '22 00:09

ColinD


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

like image 44
Simon Nickerson Avatar answered Sep 23 '22 00:09

Simon Nickerson