Java 9 ifPresentOrElse returning value

痞子三分冷 提交于 2020-04-07 07:11:00

问题


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 ?


回答1:


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 to use them here. In fact, a simple if-then-else block would be suffice. However, if you are curious of knowing how the equivalent lambda would look like, assuming there were no side effects, here it is.

return studentOpt
    .map(unused -> updateStudent(id, name))
    .orElseGet(() -> createStudent(id, name));


来源:https://stackoverflow.com/questions/53039013/java-9-ifpresentorelse-returning-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!