在 Java 8 里,引入了一个 Optional 类,该类是一个可以为 null 的容器对象。
7.1. 保证值存在
普通:
Integer thisValue;
if (Objects.nonNull(value)) {
thisValue = value;
}else {
thisValue = DEFAULT_VALUE;
}
精简:
Integer thisValue = Optional.ofNullable(value).orElse(DEFAULT_VALUE);
7.2. 保证值合法
普通:
Integer thisValue;
if (Objects.nonNull(value) && value.compareTo(MAX_VALUE) <= 0) {
thisValue = value;} else {
thisValue = MAX_VALUE;
}
精简 :
Integer thisValue = Optional.ofNullable(value)
.filter(tempValue -> tempValue.compareTo(MAX_VALUE) <= 0).orElse(MAX_VALUE);
7.3. 避免空判断
普通:
String zipcode = null;if (Objects.nonNull(user)) {
Address address = user.getAddress();
if (Objects.nonNull(address)) {
Country country = address.getCountry();
if (Objects.nonNull(country)) {
zipcode = country.getZipcode();
}
}
}
精简:
String zipcode = Optional.ofNullable(user).map(User::getAddress)
.map(Address::getCountry).map(Country::getZipcode).orElse(null);
正文完