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

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

    What helped me was a look at the source code of the two functions.

    Map - wraps the result in an Optional.

    public Optional map(Function mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
        }
    }
    

    flatMap - returns the 'raw' object

    public Optional flatMap(Function> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Objects.requireNonNull(mapper.apply(value)); //<---  returns 'raw' object
        }
    }
    

提交回复
热议问题