title: How to implement the Elvis operator in Java 8?
body: <p>I have the classic "Elvis operator" case, where I'm calling methods that each may return null and chaining them together:</p>
  
  <pre><code>thing?:nullableMethod1(a)?:nullableMethod2(b)?:nullableMethod3()
  </code></pre>
  
  <p>In Java 8, the most faithful implementation I've found is something like this:</p>
  
  <pre><code>return Optional.ofNullable(thing)
      .flatMap(x -&gt; Optional.ofNullable(x.nullableMethod1(a)))
      .flatMap(y -&gt; Optional.ofNullable(y.nullableMethod2(b)))
      .flatMap(z -&gt; Optional.ofNullable(z.nullableMethod3()))
  </code></pre>
  
  <p>I wish that Java's <code>Optional</code> had something akin to the elvis operator:</p>
  
  <pre><code>public&lt;U&gt; Optional&lt;U&gt; elvisOperator(Function&lt;? super T, ? extends U&gt; mapper) {
      return flatMap(t -&gt; Optional.ofNullable(mapper.apply(t));
  }
  </code></pre>
  
  <p>So that I wouldn't have to wrap each return value:</p>
  
  <pre><code>return Optional.ofNullable(thing)
      .elvisOperator(x -&gt; x.nullableMethod1(a))
      .elvisOperator(y -&gt; y.nullableMethod2(b))
      .elvisOperator(Z::nullableMethod3); // also nice
  </code></pre>
  
  <p>Is there a more efficient and idiomatic way to implement the Elvis operator pattern in Java 8?</p>