【问题标题】:Converting an Optional to a List将可选项转换为列表
【发布时间】:2021-03-26 02:45:11
【问题描述】:

我想将一个Optional 收集到一个List 中,这样我最终得到一个包含单个元素的列表,如果存在可选项,或者如果不存在,则为空列表。

我想出的唯一方法(在 Java 11 中)是通过 Stream:

var maybe = Optional.of("Maybe");
var list = maybe.stream().collect(Collectors.toList());

我知道,无论如何这应该是相当有效的,但我想知道,是否有一种更简单的方法可以将 Optional 转换为 List 而无需使用中间 Stream?

【问题讨论】:

  • 不,没有更简单的方法。
  • 是的。 List.of(maybe.get())。当然,这假设在可选项中确实存在 一个值。否则:var list = maybe.isPresent() ? List.of(maybe.get()) : List.of()。更轻松?也许不是。没有中间流?是的。
  • List<String> strings = Optional.ofNullable("Maybe").<List<String>>map(ImmutableList::of).orElseGet(Collections::emptyList); 够好吗?
  • 我建议List<String> maybeList = maybe.map(Collections::singletonList).orElse(Collections.emptyList()); 作为最惯用的方式...
  • 我同意@MCEmperor 的解决方案,比使用流更好!

标签: java java-stream java-11


【解决方案1】:

好的,我将其发布为答案。

List.of(maybe.get())。当然,这假设在可选项中确实存在 一个值。否则:var list = maybe.isPresent() ? List.of(maybe.get()) : List.of()

更容易吗?也许不是。是否没有中间流?是的。

【讨论】:

    【解决方案2】:

    我认为最惯用的方式是使用Optional.map

    var maybe = Optional.of("Maybe");
    var list = maybe.map(List::of).orElse(Collections.emptyList());
    

    或者,如果您不想创建一个最终可能不会被使用的空列表:

    var list = maybe.map(List::of).orElseGet(Collections::emptyList);
    

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 2013-01-11
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多