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.
If you are using Java 9, you can use
ifPresentOrElse()
method:In case you want store the value:
Another solution would be to use higher-order functions as follows
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
Then :
Update 1:
the above solution for 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;
Then could be used as:
In this new code you have 3 things:
by the way now its name is more descriptive it is actually Consumer>
See excellent Optional in Java 8 cheat sheet.
It provides all answers for most use cases.
Short summary below
ifPresent() - do something when Optional is set
filter() - reject (filter out) certain Optional values.
map() - transform value if present
orElse()/orElseGet() - turning empty Optional to default T
orElseThrow() - lazily throw exceptions on empty Optional
There isn't a great way to do it out of the box. If you want to be using your cleaner syntax on a regular basis, then you can create a utility class to help out:
Then you can use a static import elsewhere to get syntax that is close to what you're after: