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

Exception or error:

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.

How to solve:

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

Answer:

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

Answer:

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

Answer:

This should do the trick: Objects.firstNonNull(o, default)

See guava API doc

Answer:

If your object is not already an Optional, then the Optional/firstNotNull suggestions complicate what is a simple Java feature, the ternary operator:

T myVal = (val != null) ? val : defaultVal;

Including a dependency and multiple methods calls introduces as much reading complexity as the ternary operator. I would even argue that using Optional contrary to its ‘my method may or may not be returning an object’ semantics is a red flag that you are doing something wrong (just as in other cases where one abuses something contrary to that thing’s semantic meaning).

See http://alvinalexander.com/java/edu/pj/pj010018 for more discussion about the ternary operator.

Answer:

If you are only talking about Strings, there is also Apache Commons defaultString and defaultIfEmpty methods

defaultString will only give you the default on a true null whereas defaultIfEmpty will give you the default on a null or an empty string.

There is also defaultIfBlank which will give you the default even on a blank string.

e.g.

String description = "";
description = StringUtils.defaultIfBlank(description, "Theodore"); 

description will now equal “Theodore”

Edit:
Apache Commons also has an ObjectUtils class that does null defaults for fully baked objects…

Answer:

Just FYI, Java 9 has two methods that do exactly what you want:

public static <T> T requireNonNullElse(T obj, T defaultObj);

And a lazy version:

public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier)

Answer:

java.util.Objects and Guava’s optional do provide nice way for getting overriding null to default values… been using them a lot

But here is something for more imperative minded :

public static <T> T firstNotNuLL(T...args){
    for (T arg : args)
        if ( arg != null) return arg;
    throw new NullPointerException();  
}

Answer:

You may use ObjectUtils.defaultIfNull() from org.apache.commons.lang3 library:

public static <T> T defaultIfNull(T object, T defaultValue)

Answer:

Consider using the Optional built into Guava 10. You could string together multiple optionals, like Optional.fromNullable(var).orNull() or Optional.fromNullable(var).or(Optional.of(var2)).orNull()

Leave a Reply

Your email address will not be published. Required fields are marked *