Java 9 ifPresentOrElse returning value

10,391

Given that your methods updateStudent and createStudent involve some form of side effect and you should generally prefer side effect free lambdas, I don't recommend you use them here. In fact, a simple if-then-else block would be sufficient. However, if you are curious, the equivalent lambda would look like:

return studentOpt
    .map(unused -> updateStudent(id, name))
    .orElseGet(() -> createStudent(id, name));
Share:
10,391
Tyvain
Author by

Tyvain

Updated on July 23, 2022

Comments

  • Tyvain
    Tyvain over 1 year

    1/ Working code:

    public Student process (int id, name){
      Optional<Student> studentOpt = myrepo.findById(id);
      studentOpt.isPresent() {
        return updateStudent(id, name);
      } else {
       return createStudent(id, name);
      }
    

    2/ I try to change it to 'full lambdas code' (not working):

    public Student process (int id, name){
      Optional<Student> studentOpt = myrepo.findById(id);
      return studentOpt.ifPresentOrElse(student-> return updateStudent(id, name), () ->  return createStudent(id, name));
    }
    

    1/ should I change it to full lambda? what is the cleanest?

    2/ if yes, how ?

  • Gaurav
    Gaurav about 2 years
    flawless answer @Ravindra