0

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?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
zzDevzz
  • 13
  • 5

2 Answers2

0

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();
  });
adnan_e
  • 1,764
  • 2
  • 16
  • 25
0

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.

omer blechman
  • 277
  • 2
  • 16