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());
}
}