Java 8 Java 8可选orElse,而iPresent
我对可选的Java 8 Java 8可选orElse,而iPresent,java-8,optional,Java 8,Optional,我对可选的orElse方法感到非常困惑。 我使用了以下代码,尽管存在可选值,但每次都调用orElse案例: Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type); NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile,
orElse
方法感到非常困惑。
我使用了以下代码,尽管存在可选值,但每次都调用orElse
案例:
Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile, type));
我认为,
orElse
与我在第二种情况下的示例一样。我遗漏了什么?为了避免评估替代值,请使用orElseGet
:
NotificationSettings notificationSettings =
ons.orElseGet(() -> createNotificationSettings(profile, type));
没有魔法。如果调用像
orElse
这样的方法,它的所有参数都会得到热切的求值OrelGet
通过接收要延迟评估的供应商来绕过它。为了避免评估替代值,请使用OrelGet
:
NotificationSettings notificationSettings =
ons.orElseGet(() -> createNotificationSettings(profile, type));
没有魔法。如果调用像orElse
这样的方法,它的所有参数都会得到热切的求值orElseGet
通过接收要延迟评估的供应商来绕过它