I would like to migrate this legacy Java example code to Java 8.
public String getUserSex(Person person) {
if(person != null) {
if(person.getSex() != null) {
return person.getSex();
}
}
return null;
}
How to migrate this to Java 8 using Optional?
Use Optional.ofNullable and Optional.flatMap
public Optional<String> getUserSex(Person person)
{
return Optional.ofNullable(person).flatMap(
p -> Optional.ofNullable(p.getSex())
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With