Java - 如何将旧的代码块空检查切换为可选的空检查?

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

正在尝试重构我的整个项目。

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

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 return 成为可选项。您可以使用 return Optional.ofNullable(result)Persistence Class.

中执行此操作

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

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

有关更多信息,请查看一些关于可选值的教程,如下所示:https://www.baeldung.com/java-optional

但是如您所见,它不会将代码缩短很多。

如果您可以 return 来自 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()))

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