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

后端 未结 6 619
感动是毒
感动是毒 2020-11-29 16:25

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

An example would be appreciated.

6条回答
  •  佛祖请我去吃肉
    2020-11-29 17:17

    They both take a function from the type of the optional to something.

    map() applies the function "as is" on the optional you have:

    if (optional.isEmpty()) return Optional.empty();
    else return Optional.of(f(optional.get()));
    

    What happens if your function is a function from T -> Optional?
    Your result is now an Optional>!

    That's what flatMap() is about: if your function already returns an Optional, flatMap() is a bit smarter and doesn't double wrap it, returning Optional.

    It's the composition of two functional idioms: map and flatten.

提交回复
热议问题