Combining Java 8 Optionals

Debsankar Mukhopadhyay :

I have two methods in my code:

Optional<CourseId> getCourseId(){
// returns just 1 course    
}

Optional<StudentId> getStudentId(CourseId courseId){
//returns an optional studentId
}

I am trying to combine these two methods to get something like this:

Optional<CourseId> crsid = getCourseId();
if ( crsid.isPresent() ){
    return getStudentId(crsid.get());
}
else{
    return Optional.empty()
}

How can I combine the above logic into an optional map?

Adrian :

use Optional::flatMap method

return getCourseId().flatMap(id -> getStudentId(id));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130785&siteId=1