I am writing a Java method to extract a String property, called number, from a Person object.
A Person object has several properties that can be null and number belongs to house, which belongs to addresses, which belongs to metadata which finally belongs to our person.
As addresses is a list of Address objects, I want to extract the first non-null number. That is what I have so far:
public class HouseNumberResolver {
public static String numberFrom (Person person) {
return Optional.ofNullable(person)
.map(Person::getMetadata)
.map(Metadata::getAddresses)
.map(HouseNumberResolver::getFirstHouseNumber)
.orElse("");
}
private static String getFirstHouseNumber(List<Address> addresses) {
for (Address address : addresses) {
String number = Optional.ofNullable(address)
.map(Address::getHouse)
.map(House::getNumber)
.orElse(null);
if (number != null) {
return number;
}
}
return null;
}
}
However, I feel that this is quite ugly. Ideally, I wanted to have something like:
private static String getFirstHouseNumber(List<Address> addresses) {
for (Address address : addresses) {
Optional.ofNullable(address)
.map(Address::getHouse)
.map(House::getNumber)
.ifPresent(number -> return number)
.orElse(null)
}
}
That would return the number there, but it seems like this is not possible.
Any recommendations are welcome.
numberFrombut returns a string object (or do you deal with sub numbers line1a?. But more important: do not returnnullunless it is a valid member of the result set, which I argue here. \$\endgroup\$