2016-05-13 38 views
1

我很困惑於orElse方法的可選。 我用下面的代碼,雖然可選的值是本它調用orElse情況下每次:Java 8可選的orElse,而isPresent

Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type); 
NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile, type)); 

如果我重寫代碼下文中,正確的路徑(ifPresent)被選擇:

Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type); 
NotificationSettings notificationSettings = ons.isPresent() ? ons.get() : createNotificationSettings(profile, type); 

我以爲orElse就像我在第二種情況下的例子一樣。我錯過了什麼?

回答

6

爲了避免評估替代值使用orElseGet

NotificationSettings notificationSettings = 
    ons.orElseGet(() -> createNotificationSettings(profile, type)); 

沒有什麼神奇。如果你調用一個像orElse這樣的方法,所有的參數都會被急切地評估。 orElseGet通過收到一個Supplier得到懶惰評估。