如何在Java 8中更紧凑地编写此表达式?

时间:2020-11-05 11:38:12

标签: java java-8

如果使用Java 8更紧凑,我该怎么写呢?

Optional.ofNullable(city).ifPresent(c -> {
    if (!city.equalsIgnoreCase(district)) {
        address.setCity(district + ", " + c);
    }
});

1 个答案:

答案 0 :(得分:3)

正如伊兰(Eran)所说,您可以通过直接检查Optional来避免null上的虚假弯路:

if (city != null && !district.equalsIgnoreCase(city)) {
  address.setCity(district + ", " + city);
}