13

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 ?

2
  • 1
    And what exactly does "not working" mean? Please see the How to Ask article for help on building a question we can actually answer :)
    – Zephyr
    Oct 29, 2018 at 5:07
  • 2
    Remove the return calls from inside the call to ifPresentOrElse, and it should work. You might have to make id and name effectively final. Oct 29, 2018 at 5:14

1 Answer 1

31

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));
2
  • flawless answer @Ravindra
    – Gaurav
    Feb 14, 2022 at 18:34
  • THANK YOU! Been searching for hours. I miss Java 6 Jul 23, 2022 at 0:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.