下面的例子中,代码片段1和代码片段2作用等价,并且更简洁
import lombok.Data;
import java.util.Optional;
public class OptionalExample {
// String isocode2 = user.getAddress().getCountry().getIsocode()
// 通过Optional的map可以消除冗长的空值判断
public static void main(String[] args) {
User user = new User();
// 代码片段1
String isocode = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCountry)
.map(Country::getIsocode)
.orElse(null);
System.out.println("isocode:"+isocode);
// 代码片段2
if (user != null) {
Address address = user.getAddress();
if (address != null) {
Country country = address.getCountry();
if (country != null) {
String isocode2 = country.getIsocode();
System.out.println("isocode2:"+isocode2);
}
}
}
}
}
@Data
class User {
private Address address;
}
@Data
class Address {
private Country country;
}
@Data
class Country {
private String isocode;
}