Tyvain
Tyvain

Reputation: 2760

Java 9 ifPresentOrElse returning value

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);
  }

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));
}

Should I change it to full lambda? What is the cleanest? If yes, how?

Upvotes: 13

Views: 18689

Answers (2)

Agust&#237;n Ranieri
Agust&#237;n Ranieri

Reputation: 11

We must consider that .map().orElseGet() is not equivallent to a return value for .ifPresentOrElse() in all cases, because if the first branch (eg: updateStudent) returns null, second branch (eg: createStudent) would be executed.

If you are 100% sure that first branch will not return null, then both expressions are equivallent.

Upvotes: 0

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

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));

Upvotes: 31

Related Questions