title: Advantages of using a (flat)map over a simple null check?
body: <p>I was reading the below source, and I was wondering why on earth I'd use the flatmap way. As I see it a lot more objects are instantiated, code executed than in the simple null check via if statement, which will terminate on the first null and not bother to check the others and fits nice and neatly in wrapper.</p>
  
  <p>As I see it the if check is faster + more memory safe(the speed is really crucial for me as I usually only have 2-3 milliseconds for a lot of code to execute, if at all)</p>
  
  <p><strong>What are the advantages of using the "(flat)Map" optional way? Why should I consider switching to it?</strong></p>
  
  <p>From <a href="http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/" rel="nofollow">http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/</a></p>
  
  <pre><code>class Outer {
      Nested nested;
  }
  
  class Nested {
      Inner inner;
  }
  
  class Inner {
      String foo;
  }
  </code></pre>
  
  <blockquote>
    <p>In order to resolve the inner string foo of an outer instance you have to add multiple null checks to prevent possible NullPointerExceptions:</p>
  </blockquote>
  
  <pre><code>Outer outer = new Outer();
  if (outer != null &amp;&amp; outer.nested != null &amp;&amp; outer.nested.inner != null) {
      System.out.println(outer.nested.inner.foo);
  }
  </code></pre>
  
  <blockquote>
    <p>The same behavior can be obtained by utilizing optionals flatMap operation:</p>
  </blockquote>
  
  <pre><code>Optional.of(new Outer())
      .flatMap(o -&gt; Optional.ofNullable(o.nested))
      .flatMap(n -&gt; Optional.ofNullable(n.inner))
      .flatMap(i -&gt; Optional.ofNullable(i.foo))
      .ifPresent(System.out::println);
  </code></pre>