【问题标题】:Set a variable inside lambda expression [duplicate]在lambda表达式中设置一个变量[重复]
【发布时间】:2019-01-22 11:37:15
【问题描述】:

我想更新一个条目如下:

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 表达式中使用的变量应该是最终的或有效的 最终

我该如何解决这个问题?

【问题讨论】:

    标签: java java-8


    【解决方案1】:

    这里不要使用 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);
    

    【讨论】:

      【解决方案2】:

      如果初始条目存在,您实际上可以使用 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()));
      }
      

      【讨论】:

        猜你喜欢
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-13
        • 1970-01-01
        • 2011-04-19
        相关资源
        最近更新 更多