java8 orElse(null.getValue())如何处理

Jig*_*aik 2 java java-8

elseCondition当前抛出空值时是否可以在一行中写nullPointer

在我的场景中,returnValue是一个String,它为null。

我要写的条件是

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() {...}
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

elseCondition还应该用包裹Optional

Optional.ofNullable(returnValue)
        .orElse(Optional.ofNullable(elseCondition)
                        .map(ElseCodnition::getValue)
                        .orElse(null));
Run Code Online (Sandbox Code Playgroud)

也就是说,我不确定这是Optionals的好用例。