Skip to content
Advertisement

Functional style of Java 8’s Optional.ifPresent and if-not-Present?

In Java 8, I want to do something to an Optional object if it is present, and do another thing if it is not present.

JavaScript

This is not a ‘functional style’, though.

Optional has an ifPresent() method, but I am unable to chain an orElse() method.

Thus, I cannot write:

JavaScript

In reply to @assylias, I don’t think Optional.map() works for the following case:

JavaScript

In this case, when opt is present, I update its property and save to the database. When it is not available, I create a new obj and save to the database.

Note in the two lambdas I have to return null.

But when opt is present, both lambdas will be executed. obj will be updated, and a new object will be saved to the database . This is because of the return null in the first lambda. And orElseGet() will continue to execute.

Advertisement

Answer

For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives.

Here another implementation I preferred more:

JavaScript

Then:

JavaScript

Update 1:

the above solution for the traditional way of development when you have the value and want to process it but what if I want to define the functionality and the execution will be then, check below enhancement;

JavaScript

Then could be used as:

JavaScript

In this new code you have 3 things:

  1. can define the functionality before the existing of an object easy.
  2. not creating object reference for each Optional, only one, you have so less memory than less GC.
  3. it is implementing consumer for better usage with other components.

By the way, now its name is more descriptive it is actually Consumer<Optional<?>>

Advertisement