Skip to content
Advertisement

How to implement the Elvis operator in Java 8?

I have the classic “Elvis operator” case, where I’m calling methods that each may return null and chaining them together:

JavaScript

In Java 8, the most faithful implementation I’ve found is something like this:

JavaScript

I wish that Java’s Optional had something akin to the elvis operator:

JavaScript

So that I wouldn’t have to wrap each return value:

JavaScript

Is there a more efficient and idiomatic way to implement the Elvis operator pattern in Java 8?

Advertisement

Answer

Maybe I’m overlooking something, but is there a reason that you can’t use Optional#map?

The following example prints nothing, as Optional is short-circuiting in the sense that, if the value inside the Optional doesn’t exist (it’s null or the Optional is empty), it’s treated as empty.

JavaScript

For that reason, I’d think you could just do the following:

JavaScript

This would map your thing if it exists, or return an empty Optional otherwise.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement