Uses for Optional

前端 未结 14 1420
眼角桃花
眼角桃花 2020-11-22 01:01

Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional. I se

14条回答
  •  [愿得一人]
    2020-11-22 01:23

    1 - As a public method return type when the method could return null:

    Here is a good article that shows usefulness of usecase #1. There this code

    ...
    if (user != null) {
        Address address = user.getAddress();
        if (address != null) {
            Country country = address.getCountry();
            if (country != null) {
                String isocode = country.getIsocode();
                isocode = isocode.toUpperCase();
            }
        }
    }
    ...
    

    is transformed to this

    String result = Optional.ofNullable(user)
      .flatMap(User::getAddress)
      .flatMap(Address::getCountry)
      .map(Country::getIsocode)
      .orElse("default");
    

    by using Optional as a return value of respective getter methods.

提交回复
热议问题