Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code an intelligent coalesce in Java?

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?

like image 615
GarouDan Avatar asked Apr 24 '15 12:04

GarouDan


1 Answers

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)

like image 63
Peter Lawrey Avatar answered Oct 20 '22 01:10

Peter Lawrey