javajava-8option-type

Compact way to conditionally create a present or empty Optional


I want to check if a particular object size is greater than 0. If it is greater than 0 then I want to create an optional object, if not then I want to return an empty optional. This is the long version of the Java code:

if(fooA.size>0) {
    return Optional.of(new Foo());
} else {
    return Optional.empty();
}

Is there any way to compact this into one line using the Optional API introduced in Java 8?


Solution

  • Is there any way to compact this into one line using java 8's optional library?

    If you insist on using the Optional class, you could use Optional.ofNullable() and just pass it null if the condition isn't met:

    return Optional.ofNullable(fooA.size > 0 ? new Foo() : null);
    

    Note, however (as Holger correctly states) that using the Optional class doesn't give you any significant1 advantage over just replacing your if/else statement with a ternary one (as tobias_k and Holger have both done in their comments):

    return fooA.size > 0 ? Optional.of(new Foo()) : Optional.empty();
    

    1 The first line is a little shorter, which I usually consider an advantage, but an absolutely insignificant one in this case, as the length difference is negligible.