When I retrieve a Student entity from DB, the repository returns a nullable Optional<Student>
. It has a birthdate
field.
Optional<Student> getStudentById(String id);
So, how can I write in functional style a one-liner to get the birthdate of it, when it is null returns null, and when is not, return the date?
I am now with:
Date birthdate = studentRepository.getStudentById(id).isPresent() ?
studentRepository.getStudentById(id).get().getBirthdate() : null;
But I think it is ugly to use isPresent()
and ternary; it is just if/else
.
And, this will not work:
Date birthdate = studentRepository.getStudentById(id).get().getBirthdate().orElse(null); // this does not work because orElse() cannot chain with getBirthdate()
I am with Java 8.
I don't think it is possible without any overhead but I am open to suggestions.
Try this
studentRepository.getStudentById(id)
.map(Student::getBirthdate).orElse(null);
you can map
it and use orElse
to return the value if present or else provide a default:
studentRepository.getStudentById(id)
.map(Student::getBirthdate)
.orElse(defaultValue);
in your case, defaultValue
would be null
.
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