Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a more functional approach using Java Optional?

I'm trying my hand at using Optional as much as I can over normal null checks; and I ran into a suggestion by my IDE (IntelliJ):

Can be replaced by a singular expression in functional style.

Here is the code in question, the line in question:

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

I've looked a bit here, but couldn't find a usage or at least see one that would fit my case here. I'm pretty new to the lambda features.

like image 219
jacob Avatar asked Dec 04 '25 14:12

jacob


1 Answers

How about:

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

If maybeBytes contains a value, it will be passed to the function you provide to map(), and you'll get an Optional<Entry> with the result (and if maybeBytes was empty, you'll get an empty Optional<Entry>). orElseGet() will give you the contents of the Optional<Entry> if it's nonempty, and otherwise, it will give you the result of evaluating the function you pass to it (in this case, the constructor of Entry).

like image 67
Aasmund Eldhuset Avatar answered Dec 06 '25 02:12

Aasmund Eldhuset