ifPresent() is given Consumer interface
ifPresentOrElse() is given Consumer interface and Runnable interface
map() is given Function interface, and Function#apply method return
map returns Optional
flatMap() is given Function interface, and Function#apply method return Optional
flatMap returns Optional
public class Outer {
public static void main(String[] args) {
Optional<String> o = Optional.of("abc");
o.ifPresent((str) -> { System.out.println("optional value is " + str);});
o.ifPresentOrElse(str -> { System.out.println("orelse optional value is " + str);},
() -> { System.out.println("orelse optional value is empty");});
System.out.println("mapping function is "+ o.<Integer>map(str -> str.length()).get());
System.out.println("flat mapping function is "+ o.<Integer>flatMap(str -> Optional.of(str.length())).get());
o = Optional.empty();
o.ifPresent((str) -> { System.out.println("optional value is " + str);});
o.ifPresentOrElse(str -> { System.out.println("orelse optional value is " + str);},
() -> { System.out.println("orelse optional value is empty");});
}
}
optional value is abc
orelse optional value is abc
mapping function is 3
flat mapping function is 3
orelse optional value is empty