Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute logic on Optional if not present?

I want to replace the following code using java8 Optional:

public Obj getObjectFromDB() {     Obj obj = dao.find();     if (obj != null) {         obj.setAvailable(true);     } else {         logger.fatal("Object not available");     }      return obj; } 

The following pseudocode does not work as there is no orElseRun method, but anyways it illustrates my purpose:

public Optional<Obj> getObjectFromDB() {     Optional<Obj> obj = dao.find();     return obj.ifPresent(obj.setAvailable(true)).orElseRun(logger.fatal("Object not available")); } 
like image 982
membersound Avatar asked Mar 24 '15 15:03

membersound


People also ask

How do you throw an exception if optional not present?

The orElseThrow() method of java. util. Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method throws the exception generated from the specified supplier.

What does Optional get return if empty?

In Java, the Optional object is a container object that may or may not contain a value. We can replace the multiple null checks using the Optional object's isPresent method. The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.

How do I make optional isPresent false?

If you just want an Optional returning false for isPresent() , you don't need to mock the Optional at all but just create an empty one. Of course this test only tests that the mock object actually returns the stubbed return value, but you get the idea.


1 Answers

With Java 9 or higher, ifPresentOrElse is most likely what you want:

Optional<> opt = dao.find();  opt.ifPresentOrElse(obj -> obj.setAvailable(true),                     () -> logger.error("…")); 

Currying using vavr or alike might get even neater code, but I haven't tried yet.

like image 169
Andreas Avatar answered Oct 17 '22 23:10

Andreas