简体   繁体   中英

java Optional: if do something pattern

Is it able to write this code embedded into Optional method chain:

Optional<Application> appOpt = this.applicationDao.findById(application.getCode());

Application app = appOpt.orElse(Application::new);

if (!appOpt.isPresent()) {
    app.get().setUserCreation("user");
    app.get().setTimestampCreation(new Date());
}

I'd like to avoud using again the previous appOpt object. I would like to embed all this logic inside an Optional method chain.

I guess there should be another more elegant way to get it.

I've tried to play with ifPresent but it returns void and so I'm not able to chain orElse method:

appOpt.ifPresent(a -> {
    a.setUserCreation("userCreation"));
    app.setTimestampCreation(new Date());
})
.orElse(Application::new);

I hope I've explained so well.

Any ideas?

After looking again at your original code, it looks like the logic should run if the Optional is empty:

Application application = appOpt.orElseGet(() -> {
    Application app = new Application();
    app.setUserCreation("userCreation"));
    app.setTimestampCreation(new Date());
    return app;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM