Home > database >  ResponseEntity in Optional as ok or noContent, depending if present
ResponseEntity in Optional as ok or noContent, depending if present

Time:02-10

Im currently returning my content in this way:

Optional<String> data = Optional.of("bla");
Optional<ResponseEntity<?>> response = data.map(ResponseEntity::ok);
return response.orElse(ResponseEntity::noContent);

is there a way to combine the map with the orElse without saving them into a variable first?

(something like this, but without the cast problems)

Optional<String> data = Optional.of("bla");
return data.map(ResponseEntity::ok) // Type: ResponseEntity<String>
  .orElse(ResponseEntity::noContent); // Type: ResponseEntity<?> => Cast Error

This is a similar problem to

Optional.of<Object>("bla").orElse(2);

but I don't know how how to do this with a map

Optional.of("bla")
        .<ResponseEntity<?>>map(ResponseEntity::ok)
        .orElse(ResponseEntity::noContent);

does not work

CodePudding user response:

return data.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.noContent().build());

CodePudding user response:

Can you describe what your problem is exactly.

Can't you just do something like this:

return Optional.of("bla")
    .map(ResponseEntity::ok)
    .orElse(ResponseEntity::noContent);
  • Related