How to execute logic on Optional if not present?

membersound picture membersound · Mar 24, 2015 · Viewed 130.5k times · Source

I want to replace the following code using java8 Optional:

public Obj getObjectFromDB() {
    Obj obj = dao.find();
    if (obj != null) {
        obj.setAvailable(true);
    } else {
        logger.fatal("Object not available");
    }

    return obj;
}

The following pseudocode does not work as there is no orElseRun method, but anyways it illustrates my purpose:

public Optional<Obj> getObjectFromDB() {
    Optional<Obj> obj = dao.find();
    return obj.ifPresent(obj.setAvailable(true)).orElseRun(logger.fatal("Object not available"));
}

Answer

Andreas picture Andreas · Oct 10, 2016

With Java 9 or higher, ifPresentOrElse is most likely what you want:

Optional<> opt = dao.find();

opt.ifPresentOrElse(obj -> obj.setAvailable(true),
                    () -> logger.error("…"));

Currying using vavr or alike might get even neater code, but I haven't tried yet.