在Lambda表达式中设置变量

时间:2019-01-22 11:37:15

标签: java java-8

我要更新以下条目:

public Entry updateEmail(String nom, EntryRequest entryReq) {
        Optional<Entry>  optional =  entryRepository.findByNom(nom);
        Entry updatedEntry = null;
        optional.ifPresent(entry -> {
            if(!StringUtils.isEmpty(entryReq.getEmail())){
                entry.setEmail(entryReq.getEmail());
            }
            updatedEntry = save(entry);
        });
        optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
        return updatedEntry;
    }

此代码给我以下错误消息:

  

lambda表达式中使用的变量应为最终变量或有效变量   最终

我该如何解决?

2 个答案:

答案 0 :(得分:3)

请不要在这里使用lambda

Optional<Entry>  optional =  entryRepository.findByNom(nom);
Entry updatedEntry = null;
if(optional.isPresent()){
    Entry entry=optional.get();
    if(!StringUtils.isEmpty(entryReq.getEmail())){
        entry.setEmail(entryReq.getEmail());
    }
    updatedEntry = save(entry);
});
optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
return updatedEntry;

甚至更好

Optional<Entry>  optional =  entryRepository.findByNom(nom);
Entry entry=optional.orElseThrow(() -> new NotFoundException(this.getClass().getName()));
    if(!StringUtils.isEmpty(entryReq.getEmail())){
        entry.setEmail(entryReq.getEmail());
    } 
return save(entry);

答案 1 :(得分:1)

在初始条目存在的情况下,您实际上可以使用Optional的map方法来处理保存:

public Entry updateEmail(String nom, EntryRequest entryReq) {
    Optional<Entry>  optional =  entryRepository.findByNom(nom);
    Entry updatedEntry = optional.map(entry -> {
        if(!StringUtils.isEmpty(entryReq.getEmail())){
            entry.setEmail(entryReq.getEmail());
        }
        return save(entry);
    }).orElseThrow(() -> new NotFoundException(this.getClass().getName()));
    return updatedEntry;
}

更加简洁:

public Entry updateEmail(String nom, EntryRequest entryReq) {
    Optional<Entry>  optional =  entryRepository.findByNom(nom);
    return optional.map(entry -> {
        if(!StringUtils.isEmpty(entryReq.getEmail())){
            entry.setEmail(entryReq.getEmail());
        }
        return save(entry);
    }).orElseThrow(() -> new NotFoundException(this.getClass().getName()));
}
相关问题