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

JavaGuava

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

This should do the trick: Objects.firstNonNull(o, default)
See guava API doc

Solution 5 - Java

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

Solution 6 - Java

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.

Solution 7 - Java

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)

Solution 8 - Java

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

Solution 9 - Java

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

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

Solution 10 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrissView Question on Stackoverflow
Solution 1 - JavaColinDView Answer on Stackoverflow
Solution 2 - JavaSimon NickersonView Answer on Stackoverflow
Solution 3 - JavaNicolas NobelisView Answer on Stackoverflow
Solution 4 - JavaJens HoffmannView Answer on Stackoverflow
Solution 5 - JavaDaniel SchmidtView Answer on Stackoverflow
Solution 6 - JavaMonkeyWithDartsView Answer on Stackoverflow
Solution 7 - JavaZhekaKozlovView Answer on Stackoverflow
Solution 8 - Javakunwar.sangramView Answer on Stackoverflow
Solution 9 - JavaLu55View Answer on Stackoverflow
Solution 10 - JavaRayView Answer on Stackoverflow