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

smallufo picture smallufo · May 21, 2014 · Viewed 358.1k times · Source

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.

if (opt.isPresent()) {
  System.out.println("found");
} else {
  System.out.println("Not found");
}

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:

opt.ifPresent( x -> System.out.println("found " + x))
   .orElse( System.out.println("NOT FOUND"));

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

opt.map( o -> {
  System.out.println("while opt is present...");
  o.setProperty(xxx);
  dao.update(o);
  return null;
}).orElseGet( () -> {
  System.out.println("create new obj");
  dao.save(new obj);
  return null;
});

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.

Answer

ZhekaKozlov picture ZhekaKozlov · Mar 8, 2017

If you are using Java 9+, you can use ifPresentOrElse() method:

opt.ifPresentOrElse(
   value -> System.out.println("Found: " + value),
   () -> System.out.println("Not found")
);