2

I'm using Guava's Optional and I want to return Optional.absent() when string is empty or Optional.of(name) when string is not empty. Can I do it in some concise form without using ternary operator? Here's my current code:

final String name = getName();
final Optional<String> optional;
if (name.isEmpty()) {
    optional = Optional.absent();
} else {
    optional = Optional.of(name);
}

1 Answer 1

8

How about

Optional<String> optional = Optional.fromNullable(Strings.emptyToNull(name));

Guava emptyToNull

Guava fromNullable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.