Looking for a more functional approach using Java Optional?

I try to use this option as much as possible over the usual normal checks; and I came across my IDE (IntelliJ) suggestion:

Can be replaced by a singular expression in functional style.

      

Here is the code in question, the relevant line:

Entry entry = maybeBytes.isPresent() ? Entry.deserialize(maybeBytes.get()) : new Entry();

      

I looked around here a bit but couldn't find a usage or at least see one that would fit my case here. I am new to lambda functions.

+3


source to share


3 answers


How about :

Entry entry = maybeBytes.map(Entry::deserialize).orElseGet(Entry::new);

      



If it maybeBytes

contains a value, it will be passed to the function you provide map()

and you will get Optional<Entry>

with the result (and if it maybeBytes

was empty, you will get empty Optional<Entry>

). orElseGet()

will give you the content Optional<Entry>

if not empty, and otherwise it will give you the result of evaluating the function passed to it (in this case, the constructor Entry

).

+8


source


Pressing Alt + Enter when you see such suggestions will apply them and you will see the result for yourself :)



+1


source


In my case it was orElse () which suits my needs. I don't need to do any additional deserialization.

instead of isPresent () combined with get () certainly does the trick ...

return maybeBytes.isPresent() ? maybeBytes.get() : new Entry();

      

you can use

return maybeBytes.orElse(new Entry());

      

0


source







All Articles