我有一个用例,想知道如何使用Java Optional最好地编写它,以便减少空检查?
// To get first residence place for family places or empty string if null
// What if familyPlaces is null?
public String getFirstResidencePlace(FamilyPlaces familyPlaces) {
// What if getResidencePlaces() returns null in list?
List<Place> places = familyPlaces.getResidencePlaces();
for (Place place : places) {
if (place.getResidencePlaces() != null &&
!place.getResidencePlaces().isEmpty()) {
return place.getResidencePlaces().toLowerCase();
}
}
return "";
}
[这可以使用Optional
来真正处理,确保第一个调用方法导致null
值(familyPlaces.getResidencePlaces()
)的情况:
Java 9 +
Optional.ofNullable(familyPlaces.getResidencePlaces()) // Optional<List<Place>>
.stream() // Stream<List<Place>>
.flatMap(list -> list.stream()
.map(Place::getResidencePlaces)) // Stream<String>
.filter(res -> res != null && !res.isEmpty()) // Stream<String>
.map(String::toLowerCase) // Stream<String>
.findFirst() // the first String found
.orElse(""); // default return value
注意,平面映射等于:
.flatMap(List::stream) // from Stream<List<Place>> to Stream<Place>
.map(Place::getResidencePlaces) // from Stream<Place> to Stream<String>
Java 8:
Optional.ofNullable(familyPlaces.getResidencePlaces()) // Optional<List<Place>>
.orElse(Collections.emptyList()) // List<Place>
.stream() // Stream<Place>
.map(Place::getResidencePlaces) // Stream<String>
.filter(res -> res != null && !res.isEmpty()) // Stream<String>
.map(String::toLowerCase) // Stream<String>
.findFirst() // the first String found
.orElse(""); // default return value