2016-05-13 30 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得到懒惰评估。