JAVA编程技巧(七)

七、利用 Optional

在 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);
正文完
 0
admin
版权声明:本站原创文章,由 admin 于2016-01-23发表,共计852字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处:https://www.mlzj.net。