繁体   English   中英

Java - 如何将旧方式代码块 null 检查切换到可选 null 检查?

[英]Java - How to switch old way block of code null check to Optional null check?

试图重构我的整个项目。

我希望这个块更简单可选 Java 8 null 检查最后是否可能是相同的结果? 谢谢

List<EntityDto> ventolinLogs = new ArrayList<>();
 for (VentolinLog logs : ventolinLogsList) {
   for (String ventolinId : logs.getVentolinIds()) {

   Ventolin ventolin = persistence.get(Ventolin.class, ventolinId);
   String ventolinName= "";
   String ventolinFirstName= "";

   if (ventolin != null) {
     ventolinName= ventolin.getVentolinName();
     ventolinFirstName= ventolin.getFirstName();
   }

   VentolinProfile ventolinProfile = persistence.get(VentolinProfile.class, ventolinId);
   String ventolinProfileName= "";

   if (ventolinProfile != null) {
     ventolinProfileName= ventolinProfile.getName();
   }

   EntityDto LogDto = EntityDto.builder()
            .ventolinId(ventolinId)
            .ventolinName(ventolinName)
            .ventolinFirstName(ventolinFirstName)
            .ventolin

      ventolinLogs.add(LogDto);
   }
}

使 persistence.get 返回一个 Optional。 您可以在Persistence Class 中使用return Optional.ofNullable(result)来执行此操作。

在您的代码中使用现在可以使用:

Optional<VentolinProfile> ventolinProfile = persistence.get(VentolinProfile.class, ventolinId);
String ventolinProfileName = ventolinProfile.map(VentolinProfile::getName).orElse("");

有关更多信息,请查看有关此处的一些可选教程: https://www.baeldung.com/java-optional

但正如您所见,它不会大大缩短代码。

如果您可以从 Persistence class 返回一个可选项,或者像示例中一样,只创建一个可选项,您可以执行以下操作:

ventolinProfileName = Optional.ofNullable(ventolinProfile).map(VentolinProfile::getName).orElse(ventolinProfileName); // or just "" in the last brackets

我还将构建器提取到一个变量并将其传递给 lambda:

EntityDtoBuilder builder = EntityDto.builder();
Optional.ofNullable(ventolin).ifPresent(vp-> builder.ventolinName(vp.getVentolinName())
.ventolinFirstName(vp.getFirstName()))

但是您应该注意默认值,这些默认值在您的代码中初始化为空字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM