JAVA8 - Optional中map和flatMap的区别

map中获取的返回值自动被Optional包装,即返回值 -> Optional<返回值>

flatMap中返回值保持不变,但必须是Optional类型,即Optional<返回值> -> Optional<返回值>

eg:

class FlightTicketInfo {

    private String orderNumber;

    public String getOrderNumber() {
        return orderNumber;
    }

}

/** * desc : * create_user : cheng * create_date : 2018/7/4 11:21 */
public class OptionalTest {

    @Test
    public void testMap() {
        FlightTicketInfo flightTicketInfo = null;

        Optional<Optional<String>> s1 = Optional.ofNullable(flightTicketInfo).map(OptionalTest::getOrderNumber);

        Optional<String> s2 = Optional.ofNullable(flightTicketInfo).map(FlightTicketInfo::getOrderNumber);

        Optional<String> s3 = Optional.ofNullable(flightTicketInfo).flatMap(OptionalTest::getOrderNumber);
    }

    private static Optional<String> getOrderNumber(FlightTicketInfo flightTicketInfo) {
        return Optional.ofNullable(flightTicketInfo).map(f -> f.getOrderNumber());
    }

}
    原文作者:大白能
    原文地址: https://blog.csdn.net/qq_28988969/article/details/80995927
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞