Use optional to check Null pointer exception I currently have something like this:

Price price = new Price();
ActualValue actualValue = new ActualValue();
actualValue.setValue(price.getPreviousPrice().getRegion().getValue());


I want to make sure when calling getRegion() and getValue(), no NPE is thrown, trying to make it write in one line so I thought about using Optional

Currently what I have is this:

Optional.of(price)
            .flatMap(d -&gt; Optional.ofNullable(d.getPreviousPrice())
            .flatMap(p -&gt; Optional.ofNullable(p.getRegion())
                    .flatMap(m -&gt; Optional.ofNullable(m.getValue()))))
            .ifPresent(v -&gt; actualValue.setValue(v));


Looks ugly, how can I improve?
Optional.map produces a cleaner code. It's similar to flatMap except the function inside doesn't need to know about Optional. Also passing method references makes things a little bit shorter.

Optional.of(price)
        .map(Price::getPreviousPrice)
        .map(Price::getRegion)
        .map(Region::getValue)
        .ifPresent(ActualValue::setValue);