How to return value in orElse in Optional?

Krazim00da :

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 :

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; 
    });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372277&siteId=1