如何在Optional中的orElse中return取值?

How to return value in orElse in Optional?

我有可选对象

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

我有两种情况。第一个 return ResponseEntity.ok 如果对象存在,第二个是 return ResponseEntity.noContent().build()。 我有功能

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

return必要部分的点后需要写什么?

您可以使用 orElse:

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

并进一步构建默认值:

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