Home > Blockchain >  Java Optional with multiple commands and return object
Java Optional with multiple commands and return object

Time:02-11

Attempting to execute multiple commands and return an Object (ResponseEntity) using Optional.ifPresentOrElse

More complex does not work:

return ifPresentOrElse(
           repoService.findById(inId),
           i -> {
               i.setStatus(inStatus);
               repoService.save(i);
               ResponseEntity.ok().body(i);
           }, 
           () -> {
               LOG.error("Object not available");
               ResponseEntity.notFound().build();
           });

Simpler works but doesn't execute all the commands required:

Optional<I> iOptional = repoService.findById(inId);
        
return iOptional.map(i -> ResponseEntity.ok().body(i))
                .orElse(ResponseEntity.notFound().build());

Is there away to achieve this using Optional functions?

CodePudding user response:

Use Optional.map and Optional.orElseGet, like this:

var responseEntity = repoService.findById(inId)
  .map(record -> {
    record .setStatus(inStatus);
    repoService.save(record);
    return ResponseEntity.ok().body(record);
  }).orElseGet(() -> {
    LOG.error("Object not available");
    return ResponseEntity.notFound().build();
  });

CodePudding user response:

Firstly, the signature of ifPresentOrElse is:

public void ifPresentOrElse(Consumer<T> action, Runnable emptyAction)

means that you can't return the value of this function.

So you are not retuning anything when you call ResponseEntity.ok().body(i) or ResponseEntity.notFound().build(), they are just rvalues.

On the other side, the signiture of map function is:

public <U> Optional<U> map(Function<? super T,? extends U> mapper)

means that you can return the invocation of the mapper function.

  • Related