Java 8 - Difference between Optional.flatMap and Optional.map

codependent picture codependent · Jun 16, 2015 · Viewed 100.2k times · Source

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

An example would be appreciated.

Answer

assylias picture assylias · Jun 16, 2015

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.