一、使用步骤
1.应用代码
代码如下:
public class OptionalTest {
public static void main(String[] args) {
User user = new User();
int ii = Optional.ofNullable(user)
.flatMap(User::getAddress)
.flatMap(Address::getCountry)
.map(Country::getIsII).orElse(10);
System.out.println(ii);
}
}
class User {
private Address address;
public Optional<Address> getAddress() {
return Optional.ofNullable(address);
}
}
class Address {
private Country country;
public Optional<Country> getCountry() {
return Optional.ofNullable(country);
}
}
class Country {
private Integer isII;
public Integer getIsII() {
return isII;
}
}
总结
我们在编写代码的时候很多时候需要做判空处理,不然代码就会抛异常,而我们的代码则会因为做判空而显得累赘。Optional则可以很好的帮我们解决这个问题。