Tim Schwalbe
Tim Schwalbe

Reputation: 1736

Transform null check into Java 8 Optional

Can you please give an example how to transform this using 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);
            }

Up till now I do this

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

Upvotes: 1

Views: 861

Answers (1)

Eugene
Eugene

Reputation: 120848

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

Upvotes: 8

Related Questions