java8 orElse(null.getValue()) how to handle

Is this possible to write in one line when elseCondition is null currently it's throwing nullPointer

here in my scenario returnValue is a String and it is null.

The conditions which i want to write is as

if (returnValue != null) {
    return returnValue;
} else if (elseCondition != null) {
    return elseCondition.getValue();
} else {
    return null;

Optional.ofNullable(returnValue).orElse(elseCondition.getValue()) //throws nullPointer as elseCondition is null

class ElseCodnition {
    private  String value;

    getValue() {...}

3 answers

  • answered 2019-04-15 05:54 Eran

    elseCondition should also be wrapped with an Optional:


    That said, I'm not sure this is a good use case of Optionals.

  • answered 2019-04-15 06:14 Naman

    I would have preferably used the ternary operator as:

    return (returnValue != null) ? returnValue : 
            ((elseCondition != null) ? elseCondition.getValue() : null);

    Molding conditional branches into chained Optionals doesn't sound a good for them.

  • answered 2019-04-15 10:51 Adrian

    that certainly isn't a job for Optional, instead you can create a method which calls an object getter avoiding NPE:

    static <T, R> R applyIfNotNull(T obj, Function<T, R> function) {
        return obj != null ? function.apply(obj) : null;

    and the use case

    return returnValue != null ? returnValue : applyIfNotNull(elseCondition, ElseCondition::getValue);