Search code examples
javajava-8option-type

What is the difference between Optional.flatMap and Optional.map?


What's the difference between these two methods: Optional.flatMap() and Optional.map()?

An example would be appreciated.


Solution

  • Use map if the function returns the object you need or flatMap if the function returns an Optional. For example:

    public static void main(String[] args) {
      Optional<String> s = Optional.of("input");
      System.out.println(s.map(Test::getOutput));
      System.out.println(s.flatMap(Test::getOutputOpt));
    }
    
    static String getOutput(String input) {
      return input == null ? null : "output for " + input;
    }
    
    static Optional<String> getOutputOpt(String input) {
      return input == null ? Optional.empty() : Optional.of("output for " + input);
    }
    

    Both print statements print the same thing.