代码之家  ›  专栏  ›  技术社区  ›  DilTeam

在Java 8中用“可选”删除嵌入的空校验

  •  15
  • DilTeam  · 技术社区  · 6 年前

    我替换了以下代码:

    if (status.getPlace() == null) {
        row.set("CountryCode", "Unknown");
        row.set("Country", "Unknown");
    } else {
        if (status.getPlace().getCountryCode() == null) {
            row.set("CountryCode", "Unknown");
        } else {
            row.set("CountryCode", status.getPlace().getCountryCode());
        }
        if (status.getPlace().getCountry() == null) {
            row.set("Country", "Unknown");
        } else {
            row.set("Country", status.getPlace().getCountry());
        }
    }
    

    有了这个:

    String countryCode = Optional.ofNullable(status.getPlace())
            .filter(p -> p.getCountryCode() != null)
            .map(Place::getCountryCode)
            .orElse("Unknown");
    row.set("CountryCode", countryCode);
    
    String country = Optional.ofNullable(status.getPlace())
            .filter(p -> p.getCountry() != null)
            .map(Place::getCountry)
            .orElse("Unknown");
    row.set("Country", country);
    

    它按预期工作,但不知何故我认为我可以做得更好。我在那里还有一张“空”的支票。

    .filter(p -> p.getCountryCode() != null)
    

    有没有办法避免以上的空检查?

    2 回复  |  直到 6 年前
        1
  •  17
  •   Pankaj Singhal    6 年前

    你不需要空支票- .filter(p -> p.getCountry() != null) . 删除这个,您的代码就可以正常工作了。

    Optional.map() 返回 Optional 实例本身。所以不需要应用空检查。

        2
  •  9
  •   Ousmane D.    6 年前

    你不需要 filter 操作。如果打电话给 Place::getCountryCode Place::getCountry 退货 null 然后返回一个空的可选参数,这意味着 orElse 将调用方法来检索替代值。