Java 9 ifPresentOrElse returning value

后端 未结 1 2054
谎友^
谎友^ 2021-01-19 13:08

1/ Working code:

public Student process (int id, name){
  Optional studentOpt = myrepo.findById(id);
  studentOpt.isPresent() {
    return upd         


        
1条回答
  •  囚心锁ツ
    2021-01-19 13:26

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

    0 讨论(0)
提交回复
热议问题