user12051965 :
I have the following
class Person
private String firstName;
private String familyName;
// Setters and Getters
And I have the following method
public String getFullName(Optional<Person> persons) {
return persons
.map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid");
}
I just want to check if either first or last name is null
, display "Invalid"
for that person. I was thinking to add a method for validation but I am sure there is an easier way I cannot think about.
YCF_L :
You are looking to Optional::filter
, before the map:
return persons
.filter(person -> person.getFamilyName() != null && person.getFirstName() != null)
.map(person -> person.getFirstName() + " " + person.getFamilyName())
.orElse("Invalid");
Which mean, if the family and first names are not null then create your concatination, otherwise return an Invalid message, or you can even throw an exception by using orElseThrow
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=409233&siteId=1