Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 9 ifPresentOrElse returning value

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 ?

like image 484
Tyvain Avatar asked Oct 29 '18 05:10

Tyvain


People also ask

How do I return an ifPresentOrElse value?

ifPresentOrElse() method checks if the value is present, apply action with value, else return empty action whereas Optional.or() method checks if the value is present, return option contains value, else return Optional applies to Supplier funciton.

Which of the following describes the ifPresentOrElse () method of optional class?

Q 7 - Which of the following correctly describes the ifPresentOrElse() method of Optional class? A - If a value is present, it returns a sequential Stream containing only that value, otherwise returns an empty Stream.

What is optional ofNullable in Java?

The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned. public static <T> Optional<T> ofNullable(T value)


1 Answers

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));
like image 133
Ravindra Ranwala Avatar answered Oct 16 '22 10:10

Ravindra Ranwala