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

后端 未结 6 618
感动是毒
感动是毒 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:18

    • Optional.map():

    Takes every element and if the value exists, it is passed to the function:

    Optional optionalValue = ...;
    Optional added = optionalValue.map(results::add);
    

    Now added has one of three values: true or false wrapped into an Optional , if optionalValue was present, or an empty Optional otherwise.

    If you don't need to process the result you can simply use ifPresent(), it doesn't have return value:

    optionalValue.ifPresent(results::add); 
    
    • Optional.flatMap():

    Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.

    You can use it for composing optional value functions calls.

    Suppose we have methods:

    public static Optional inverse(Double x) {
        return x == 0 ? Optional.empty() : Optional.of(1 / x);
    }
    
    public static Optional squareRoot(Double x) {
        return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
    }
    

    Then you can compute the square root of the inverse, like:

    Optional result = inverse(-4.0).flatMap(MyMath::squareRoot);
    

    or, if you prefer:

    Optional result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);
    

    If either the inverse() or the squareRoot() returns Optional.empty(), the result is empty.

提交回复
热议问题