How to code an intelligent coalesce in Java?
Asked Answered
Q

1

6

object.getProperty().getSubProperty().getSubSubProperty();

Consider the code above. An object has a property, that has a subProperty, that has a subSubProperty, that can be accessed with getter methods.

What can we do in Java to achieve something like:

Util.coalesce(object.getProperty().getSubProperty().getSubSubProperty(), defaultSubSubProperty);

org.apache.commons.lang3.ObjectUtils.defaultIfNull has something like this. But the problem with this method is that it just works when property and subProperty are not null. I would like a way to get subSubProperty or defaultSubSubProperty even when property and subProperty are null.

How can we do this?

Quipu answered 24/4, 2015 at 12:4 Comment(0)
M
11

You can use Optional in Java 8.

String s = Optional.ofNullable(object)
                   .map(Type::getProperty)
                   .map(Type2::getSubProperty)
                   .map(Type3::getSubSubProperty)
                   .orElse(defaultValue);

You can also use orElseGet(Supplier) or orElseThrow(Throwable)

Mirellamirelle answered 24/4, 2015 at 12:6 Comment(3)
Wonderfull. But I still have a problem. Here, the production Java is Java 7, can we use this in Java 7 using a jar or something like this?Quipu
@Quipu in theory, there is backports of the library but I haven't used any. Without the syntactic sugar I imagine using a library to be more painful than writing it yourself.Mirellamirelle
@Quipu You can still use Guava's Optional (ofNullable -> fromNullable, map -> transform), but you'll have to expand all the method references to anonymous subclasses, which will make your code horribly big.Trichloride

© 2022 - 2024 — McMap. All rights reserved.