Avoiding Using .get and Optional.isPresent Options

public ValueA map(ValueB valueB, Date date) { Optional<ValueC> valueCOpt = find(valueB); if (valueCOpt.isPresent()) { ValueC valueC = valueCOpt.get(); // call many getters on valueC and do a lot of logic with it. return map(/*some parameters*/); } return null; } 

That seems pretty ugly. The advantage of optionals has completely disappeared here. I read that it is better to use map or flatMap instead of get . But is it really useful if I replace each recipient, for example

 valueC.getFieldA() 

with

 valueCOpt.map(ValueC::getFieldA) 

Do you know some general or best practices here?

+5
source share
2 answers

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 matching function is evaluated only if the option is not empty, otherwise the result remains empty. orElse(null) will return null if optional is empty.

+7
source

You need to match, then 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 which case its null

+3
source

Source: https://habr.com/ru/post/1266294/


All Articles