debugjavaMinor
Use optional to check Null pointer exception
Viewed 0 times
checkexceptionnullpointeroptionaluse
Problem
I currently have something like this:
I want to make sure when calling
Currently what I have is this:
Looks ugly, how can I improve?
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 OptionalCurrently what I have is this:
Optional.of(price)
.flatMap(d -> Optional.ofNullable(d.getPreviousPrice())
.flatMap(p -> Optional.ofNullable(p.getRegion())
.flatMap(m -> Optional.ofNullable(m.getValue()))))
.ifPresent(v -> actualValue.setValue(v));Looks ugly, how can I improve?
Solution
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);Code Snippets
Optional.of(price)
.map(Price::getPreviousPrice)
.map(Price::getRegion)
.map(Region::getValue)
.ifPresent(ActualValue::setValue);Context
StackExchange Code Review Q#153949, answer score: 7
Revisions (0)
No revisions yet.