Reputation: 147
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.
Upvotes: 1
Views: 1597
Reputation: 7279
Another functional approach.
First create a predicate builder method for required field validation:
public static <T, F> Predicate<T> hasRequiredValue(Function<T, F> fieldGetter) {
return fieldGetter.andThen(Objects::nonNull)::apply;
}
And modify the getFullName
a little bit:
public Optional<String> getFullName(Person person) {
return Optional.ofNullable(person)
.filter(hasRequiredValue(Person::getFamilyName))
.filter(hasRequiredValue(Person::getFirstName))
.map(p -> p.getFirstName() + " " + p.getFamilyName());
}
Then use it as follows:
Person person = ...
String fullName = getFullName(person).orElse("Invalid");
Upvotes: 1
Reputation: 59988
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
Upvotes: 4
Reputation: 26046
You can use filter for that:
public String getFullName(Optional<Person> persons) {
return persons
.filter(person -> Objects.nonNull(person.getFirstName()) && Objects.nonNull(person.getFamilyName()))
.map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid");
}
Upvotes: 1