将null检查转换为Java 8可选

时间:2017-06-29 10:59:19

标签: java-8 optional

请举例说明如何使用Java 8 Optional进行转换。

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

1 个答案:

答案 0 :(得分:8)

export DYLD_LIBRARY_PATH=path_to_anaconda3/envs/myEnv/lib:$LD_LIBRARY_PATH