我只想看看我做得对不对。这是使用可选的正确方式,还是可以改进?
String longitudeResult = "Address_Longitude is empty or null;";
String latitudeResult = "Address_Latitude is empty or null;";
if (Optional.ofNullable(location).isPresent()) {
Optional<Double> longitude = Optional.ofNullable(location.getLongitude());
Optional<Double> latitude = Optional.ofNullable(location.getLatitude());
if (longitude.isPresent()) {
longitudeResult = longitude.get().toString();
}
if (latitude.isPresent()) {
latitudeResult = latitude.get().toString();
}
}发布于 2017-06-29 09:41:13
如果您不使用Optional的组合子,那么它就没有意义:
Optional<Location> locationOptional = Optional.ofNullable(location);
String longitudeResult = locationOptional
.map(Location::getLongitude)
.map(Object::toString)
.orElse("Address_Longitude is empty or null;");
String latitudeResult = locationOptional
.map(Location::getLatitude)
.map(Object::toString)
.orElse("Address_Latitude is empty or null;");发布于 2017-06-29 09:58:46
这似乎没有错,但您可以使用ifPresent链接您的调用。就像这样:
Optional.ofNullable(location).ifPresent(location -> {
Optional.ofNullable(location.getLatitude()).ifPresent(
latitude -> latitudeResult = latitude.get().toString());
Optional.ofNullable(location.getLongitude().ifPresent(
longitude -> longitudeResult = longitude.get().toString());
});更短的代码对我来说总是更好。
PS.:这段代码没有被编译器模仿。
https://stackoverflow.com/questions/44821253
复制相似问题