title: Method return if Java 8's Optional is present
body: <p>In Java 8, is there a way to force a method return if an <code>Optional</code> is present?
  I would guess that the answer is no. But then how to avoid using <code>isPresent()</code> and <code>get()</code> in the following code?</p>
  
  <pre class="lang-java prettyprint-override"><code>public Bar myMethod(){
      if(condition){
          Optional&lt;Foo&gt; foo = getOptionalFoo();
          if(foo.isPresent()){
              return foo.get().getBar();
          }
      }
  
      return getOtherBar();
  }
  </code></pre>
  
  <p>One solution would be to write :</p>
  
  <pre><code>public Bar myMethod(){
      if(condition){
          return getOptionalFoo()
                  .map(Foo::getBar)
                  .orElseGet(() -&gt; getOtherBar());
      }
  
      return getOtherBar();
  }
  </code></pre>
  
  <p>But it doesn't seem like a good idea because now we write twice the call to <code>getOtherBar</code>. Is there a way to avoid this?</p>
  
  <p>EDIT: I also thought of</p>
  
  <pre><code>public Bar myMethod(){
      //Or a ternary operator but there are hard to read when they make long lines
      Optional&lt;Foo&gt; foo;
      if(condition){
          foo = getOptionalFoo();
      } else {
          foo = Optional.empty();
      }
  
      return foo.map(Foo::getBar)
          .orElseGet(() -&gt; getOtherBar());
  }
  </code></pre>
  
  <p>But the issue here is that we create a useless empty <code>Optional</code> and chain methods to it. If the condition is not met 99% of the time, this make it quite less efficient than the original code (especially if we have several <code>map()</code> and <code>filter()</code>).</p>
  
  <p>NOTE: I gave a basic example, in reality in our code we have more conditions that depend on the results of other calls (which depend of foo).</p>