简体   繁体   English

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

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

Trying to refactor my whole project.试图重构我的整个项目。

l want this block to be simpler with Optional Java 8 null checks if possible to be the same results at the end?我希望这个块更简单可选 Java 8 null 检查最后是否可能是相同的结果? Thanks谢谢

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);
   }
}

Make persistence.get return an Optional.使 persistence.get 返回一个 Optional。 You can use return Optional.ofNullable(result) to do this in your Persistence Class.您可以在Persistence Class 中使用return Optional.ofNullable(result)来执行此操作。

In your code use can now use:在您的代码中使用现在可以使用:

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

For more information check out some tutorials on optionals like here: https://www.baeldung.com/java-optional有关更多信息,请查看有关此处的一些可选教程: https://www.baeldung.com/java-optional

But as you see, it won't shorten the code very much.但正如您所见,它不会大大缩短代码。

In case you can return an optional from the Persistence class or, like in the example, just create an optional, you can do the following:如果您可以从 Persistence class 返回一个可选项,或者像示例中一样,只创建一个可选项,您可以执行以下操作:

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

I would also extract the builder to a variable and pass it to a lambda:我还将构建器提取到一个变量并将其传递给 lambda:

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

But you should take care of the default values, which are initialized as empty strings in your code但是您应该注意默认值,这些默认值在您的代码中初始化为空字符串

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

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