如果使用Java 8更紧凑,我该怎么写呢?
Optional.ofNullable(city).ifPresent(c -> {
if (!city.equalsIgnoreCase(district)) {
address.setCity(district + ", " + c);
}
});
答案 0 :(得分:3)
正如伊兰(Eran)所说,您可以通过直接检查Optional
来避免null
上的虚假弯路:
if (city != null && !district.equalsIgnoreCase(city)) {
address.setCity(district + ", " + city);
}