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