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);
我的愚见是,'Optional.ofNullable(富).isPresent()'是'比富!= null'和'雪上加霜orElse(null)'只是打破了'Optional'的目的。我希望你只是简单地提出你的问题,而不是真正的代码,因为你可以清楚地看到第二个选项比第一个选项更加冗长和无用的复杂。 –
我看不到一个优于香草空检查的优势。有人可以解释可选的好处和用例吗? – TimSchwalbe
我看到使用'Optional'作为返回参数的好处。你在你的interfaces/api中声明,你返回'Optional