1

I have Optional object

Optional<Instrument> instrument = instrumentService.findOne(id);

And i have two scenario. First return ResponseEntity.ok if object is present and second is return ResponseEntity.noContent().build(). I have function

instrument.map(instrument1 -> {
            return ResponseEntity.ok(instrumentMapper.toDto(instrumentRepository.save(instrument1)));
        })
        .//return noContent here;

What i need to write after dot to return necessary part?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
Krazim00da
  • 307
  • 1
  • 5
  • 14
  • use `orElseGet(() -> ResponseEntity.no Content().build())` – qutax Mar 26 '20 at 09:53
  • you need to start writing with the API that you want to use `orElse` first and then see what arguments does it accept as values – Naman Mar 26 '20 at 10:02

1 Answers1

1

You can use orElse:

return instrument
    .map(instrument1 -> instrument1 -> { 
        instrument1.setValue(value); 
        return ResponseEntity.ok(instrumentMapper.toDto(instrumentRepository.save(instrument1))); })
    .orElse(ResponseEntity.noContent().build());

And for further building the default value:

return instrument
    .map(instrument1 -> instrument1 -> { 
        instrument1.setValue(value); 
        return ResponseEntity.ok(instrumentMapper.toDto(instrumentRepository.save(instrument1))); })
    .orElseGet(() -> {
        Intrument inst = new Intrument(); 
        inst.setTitle("Not found"); 
        return inst; 
    });
Andronicus
  • 25,419
  • 17
  • 47
  • 88