Skip to content
Advertisement

Java 8 Optional: combine two possibly null object

I have to ensure if two values are non null. When the first and second have non null values, pass first as argument to second. If one of them are null value, then return false. This can be done in the following piece of code:

JavaScript

It can also be done in short form:

JavaScript

I was wondering how to do this in fluent form with Optional.

Advertisement

Answer

You could try something like this:

JavaScript

map() applies the lambda if value is present and returns a new Optional.ofNullable() or otherwise returns an empty Optional. So in the end you have an empty Optional if either value was null or a non-empty one.

If you have a look at the source code for those methods, it basically is equivalent to this:

JavaScript
Advertisement