How to avoid using Optional.get and Optional.isPresent

You can use

public ValueA map(ValueB valueB, Date date) {
    return find(valueB)
        .map(valueC -> {
            // call many getters on valueC and do a lot of logic with it.
            return map(/*some parameters*/);
        })
        .orElse(null);
}

the key point is that the mapping function is only evaluated, if the optional is not empty, otherwise, the result stays an empty optional. orElse(null) will return null if the optional is empty.


What you need is to map, then a orElse(), or orElseThrow() if you need an exception

ValueA valueA = valueCOpt.map(valueC -> mapToValue(valueC))
       .orElse(null);

orElse() is used when you need a default value, in this case its null