Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional<T> when isPresent() get property or null when it is null; functional style in Java 8

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.

like image 203
WesternGun Avatar asked Dec 11 '22 04:12

WesternGun


2 Answers

Try this

studentRepository.getStudentById(id)
           .map(Student::getBirthdate).orElse(null);
like image 172
Hadi J Avatar answered Dec 21 '22 22:12

Hadi J


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.

like image 30
Ousmane D. Avatar answered Dec 21 '22 23:12

Ousmane D.