Search code examples
javajava-8option-type

How to execute logic on Optional if not present?


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

Solution

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