-1

I know there are multiple questions on SO which would closely resemble this question, but I couldn't find the solution that I was hoping to get.

My use-case is pretty trivial here. I have an Optional object and from the Optiona object I wanted to return a value if the object inside the Optional is present. For ex, I want to do something like this:

private String getUserName(String id) {
       // this doesn't work
        return fetchUser(id).ifPresent(user -> user.getName()).orElse("DEFAULT_NAME");
    }

    private Optional<User> fetchUser(String id) {
        try {
            return Optional.ofNullable(searchUser(id));
        } catch (Exception e) {
            LOGGER.error("User not found with id {}", id);
            return Optional.empty();
        }
    }

I am of course trying to avoid the if block here also I understand that ifPresent takes a Consumer and hence anything inside ifPresent will not return any value. But is there a way to achieve this in a more elegant fashion like above. The work around to this is of course to re-write the code like below:

private String getUserName(String id) {
//      return fetchUser(id).ifPresent(user -> user.getName()).orElse("DEFAULT_NAME");
        Optional<User> user = fetchUser(id);
        if(user.isPresent()) {
            return user.get().getName();
        } else {
            return "DEFAULT_NAME";
        }
    }

I am just trying to find a way to avoid writing if-else

RDM
  • 1,136
  • 3
  • 28
  • 50
  • Your question is "how to use `ifPresent`" but your problem is actually solved by using `map` instead of `ifPresent`, since you want to return a value. So this is an [XY problem](https://xyproblem.info/) - you might have found an existing answer which solves your problem if you searched for the problem (["java return from optional"](https://stackoverflow.com/search?q=%5Bjava%5D+return+from+optional)) instead of your attempted solution (`isPresent`). – kaya3 May 04 '21 at 16:11
  • 1
    See the second answer on this question, using `map` and `orElse`. [Returning from Java Optional ifPresent()](https://stackoverflow.com/questions/54878076/returning-from-java-optional-ifpresent) – kaya3 May 04 '21 at 16:19

1 Answers1

9

Use Optional#map:

return fetchUser(id).map(User::getName).orElse("DEFAULT_NAME");
Unmitigated
  • 76,500
  • 11
  • 62
  • 80