java - How to execute logic on Optional if not present? -
i want replace 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 not work there no orelserun
method, anyways illustrates purpose:
public optional<obj> getobjectfromdb() { optional<obj> obj = dao.find(); return obj.ifpresent(obj.setavailable(true)).orelserun(logger.fatal("object not available")); }
i don't think can in single statement. better do:
if (!obj.ispresent()) { logger.fatal(...); } else { obj.get().setavailable(true); } return obj;
Comments
Post a Comment