2017-06-29 62 views
1

您可以举一个例子来说明如何使用Java 8进行转换。将null转换为Java 8可选

  Motion motion = new Motion(); 

      if (null!= site.getLocation() && null != site.getLocation().getLatitude() && null != site.getLocation().getLongitude()) { 
       Point p = GeoJson.point(site.getLocation().getLatitude(), site.getLocation().getLongitude()); 
       motion.setLocation(p); 
      } 

到现在为止我做这个

Motion motion = new Motion(); 
    Optional<Location> locationOptional = Optional.ofNullable(site.getLocation()); 
    Point p = locationOptional 
      .map(location -> { 
        if (Optional.ofNullable(location.getLatitude()).isPresent() && Optional.ofNullable(location.getLongitude()).isPresent()) { 
         return GeoJson.point(location.getLatitude(), location.getLongitude()); 
        } 
        return null; 
       }) 
     .orElse(null); 
    motion.setLocation(p); 
+5

我的愚见是,'Optional.ofNullable(富).isPresent()'是'比富!= null'和'雪上加霜orElse(null)'只是打破了'Optional'的目的。我希望你只是简单地提出你的问题,而不是真正的代码,因为你可以清楚地看到第二个选项比第一个选项更加冗长和无用的复杂。 –

+0

我看不到一个优于香草空检查的优势。有人可以解释可选的好处和用例吗? – TimSchwalbe

+3

我看到使用'Optional'作为返回参数的好处。你在你的interfaces/api中声明,你返回'Optional '而不是'Object'来礼貌地通知下面的开发者与那个API接口,他们需要做一个空的检查。在处理链式方法时''可选'也很整洁。但海事组织,应该没有任何理由宣布当地的“可选”。 –

回答

8
GeoJson geoJson = 
    Optional.ofNullable(s.getLocation()) 
      .filter(l -> l.getLatitude() != null) 
      .filter(l -> l.getLongitude() != null) 
      .map(l -> GeoJson.point(l.getLatitude(), l.getLongitude())) 
      .orElse(null); 
+1

,或者直接用'orElse(null)'设置值, ifPresent(运动:: setLocation)' – ledniov