Sasha
Sasha

Reputation: 81

how to write code in java 8 use Optionals

I have a code like this. How can it be rewritten more correctly?

Optional<String> getNameBySiiPriorityInfo(Optional<SiiPriorityInfo> siiPriorityInfo){
    return siiPriorityInfo.isPresent() ? Optional.ofNullable(siiPriorityInfo.get().getName()) : Optional.empty();
}

Upvotes: 0

Views: 73

Answers (1)

khelwood
khelwood

Reputation: 59113

If you have an optional and you want to get another optional given by performing an operation on the object inside the optional, use map.

return siiPriorityInfo.map(SiiPriorityInfo::getName);

Upvotes: 6

Related Questions