Michal Kordas
Michal Kordas

Reputation: 10925

Concise way of creating Guava's Optional based on String being empty or not

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);
}

Upvotes: 2

Views: 147

Answers (1)

AlmasB
AlmasB

Reputation: 3407

How about

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

Guava emptyToNull

Guava fromNullable

Upvotes: 8

Related Questions