package com.nequissimus.java8;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

final class OptionalStuff {
  /**
  * "Expensive" call to an API, used for {Optional#orElseGet}
  */
  static class Fallback implements Supplier<Integer> {
    public Integer get() {
      try {
        Thread.sleep(10_000);
      } catch (InterruptedException e) {}

      return 0;
    }
  }

  /**
  * Function that may return a String or null
  */
  static String randomString() {
    if (System.currentTimeMillis() % 2 == 0) {
      return null;
    } else {
      return "lasjlkasjdlas";
    }
  }

  public static void main(String[] args) {
    final Function<String, Optional<Integer>> len = x -> Optional.of(x.length());

    final Optional<String> oStr = Optional.ofNullable(randomString());
    final Optional<Integer> oLen = oStr.flatMap(len);

    System.out.println("Length = " + oLen.orElseGet(new Fallback()));
  }
}

@@ -153,16 +153,145 @@
 Stuff %7B%0A
+  static int expensiveCall() %7B%0A    try %7B%0A      Thread.sleep(10_000);%0A    %7D catch (InterruptedException e) %7B%7D%0A%0A    return 0;%0A  %7D%0A%0A
   /**%0A  
@@ -447,101 +447,30 @@
     
-try %7B%0A        Thread.sleep(10_000);%0A      %7D catch (InterruptedException e) %7B%7D%0A%0A      return 0
+return expensiveCall()
 ;%0A  
@@ -745,24 +745,78 @@
 nal 
-Func
+Op
 tion
+al
 %3CString
-,
+%3E oStr = Optional.ofNullable(randomString());%0A    final
  Opt
@@ -833,101 +833,532 @@
 ger%3E
-%3E l
+ oL
 en = 
-x -%3E Optional.of(x.length());%0A%0A    final Optional%3C
+oStr.map(x -%3E x.length());%0A%0A    System.out.println(%22Length = %22 + oLen.orElseGet(new Fallback()));%0A  %7D%0A%0A  /**%0A  * Pre-Java 8 with try/catch%0A  */%0A  public static void oldWayTry() throws Exception %7B%0A    final 
 String
-%3E oStr = Optional.ofNullable(
+ r = randomString();%0A    int l;%0A%0A    try %7B%0A      l = r.length();%0A    %7D catch (Exception e) %7B%0A      l = expensiveCall();%0A    %7D%0A%0A    System.out.println(%22Length = %22 + l);%0A  %7D%0A%0A  /**%0A  * Initialize to %22null%22-value, then replace with proper value%0A  */%0A  public static void oldWayInit() %7B%0A    final String r = 
 rand
@@ -1371,133 +1371,389 @@
 ng()
-)
 ;%0A    
-f
 in
-al Optional%3CInteger%3E oLen = oStr.flatMap(len);%0A%0A    System.out.println(%22Length = %22 + oLen.orElseGet(new Fallback())
+t l = expensiveCall();%0A%0A    if (r != null) %7B%0A      l = r.length();%0A    %7D%0A%0A    System.out.println(%22Length = %22 + l);%0A  %7D%0A%0A  /**%0A  * Pre-Java 8 with a guard%0A  */%0A  public static void oldWayGuard() %7B%0A    final String r = randomString();%0A    int l;%0A%0A    if (r != null) %7B%0A      l = r.length();%0A    %7D else %7B%0A      l = expensiveCall();%0A    %7D%0A%0A    System.out.println(%22Length = %22 + l
 );%0A 

Use map, instead of flatMap and add 'old' ways of handling it