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.
An alternative is:
I don't think it improves readability though.
Or as Marko suggested, use a ternary operator:
Another solution could be following:
This is how you use it:
Or in case you in case of the opposite use case is true:
This are the ingredients:
The "cosmetically" enhanced Function interface.
And the Optional wrapper class for enhancement:
This should do the trick and could serve as a basic template how to deal with such requirements.
The basic idea here is following. In a non functional style programming world you would probably implement a method taking two parameter where the first is a kind of runnable code which should be executed in case the value is available and the other parameter is the runnable code which should be run in case the value is not available. For the sake of better readability, you can use curring to split the function of two parameter in two functions of one parameter each. This is what I basically did here.
Hint: Opt also provides the other use case where you want to execute a piece of code just in case the value is not available. This could be done also via Optional.filter.stuff but I found this much more readable.
Hope that helps!
Good programming :-)