【问题标题】:Can this usage of Optional be made more functional是否可以使 Optional 的这种用法更具功能性
【发布时间】:2019-12-24 18:52:27
【问题描述】:

是否可以使Optional 的这种用法具有更多功能,即将isEmpty() 的调用替换为处理空情况的可选方法之一?

public Iterable<User> getOrganisationUsers(final String organisationId) {

  Optional<Organisation> org = organisationRepository.findById(organisationId);

  if (org.isEmpty()) {
    return Collections.emptyList();
  }
  return org.get().getUsers();
}

【问题讨论】:

    标签: java optional


    【解决方案1】:

    您的代码的更多功能版本:

    return organisationRepository.findById(organisationId)
            .map(Organisation::getUsers)
            .orElseGet(Collections::emptyList);
    

    【讨论】:

    【解决方案2】:

    试试

    return org.map(Organisation::getUsers).orElse(Collections.emptyList());
    

    【讨论】:

      【解决方案3】:

      this answer

      您可以使用Optional#orElse 方法。

      在你的情况下,它会是:

      return organisationRepository.findById(organisationId).map(org->org.getUsers()).orElse(Collections.emptyList());
      

      【讨论】:

      • 啊,比我快4秒
      • @AbishekAditya 好像我很幸运 :)
      • 编译错误,因为Collections.emptyList() 没有返回Organisation 对象。
      • 这不会编译。 orElse 需要 Organisation 作为参数并且你传递集合。
      • 什么是getValue()
      猜你喜欢
      • 2016-12-26
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      相关资源
      最近更新 更多