【问题标题】:Optional - Collect values extracted from two Optionals into an immutable SetOptional - 将从两个 Optional 中提取的值收集到一个不可变的 Set 中
【发布时间】:2022-11-19 01:07:53
【问题描述】:

我希望避免出现多个 if-else 情况。有没有更简洁的方法来编写下面的代码?

private Set<String> getValues(Optional<String> one, Optional<String> two) {
    if (one.isPresent() && two.isPresent()) {
        return ImmutableSet.of(one.get(), two.get());
    } else if (one.isPresent()) {
        return ImmutableSet.of(one.get());
    } else {
        return two.isPresent() ? ImmutableSet.of(two.get()) : ImmutableSet.of();
    }
}

【问题讨论】:

  • 那是番石榴ImmutableSet,还是您在使用其他库?
  • 是的,是番石榴
  • 您使用的是什么版本的java?
  • 我正在使用 Java 11

标签: java set option-type guava immutable-collections


【解决方案1】:

最简单的解决方案是使用Optional.stream(),jdk9+:

   private Set<String> getValuesJdk9(Optional<String> one, Optional<String> two) {
       return Stream.concat(one.stream(), two.stream())
              .collect(Collectors.toSet());
    }

你可以阅读更多here

如果您仍在使用 JDK8:

 private Set<String> getValuesJdk8(Optional<String> one, Optional<String> two) {
       return Stream.of(one, two)
              .filter(Optional::isPresent)
              .map(Optional::get)
              .collect(Collectors.toSet());
    }

还有一个极端的版本,当你可以传递任意数量的参数时

   private Set<String> getAllValues(Optional<String>... options) {
        return Arrays.stream(options).flatMap(Optional::stream)
                .collect(Collectors.toSet());
    }

【讨论】:

  • Collectors.toSet() -> Collectors.toUnmodifiableSet(),JDK10+
【解决方案2】:

长话短说

首先,它是一个灰心练习绕过Optionals。

看:Uses for Optional。

相反,您可以提供 Optional 的 Supplier 并在您的方法中对其进行评估。

这个问题可以概括为:“从非空 Optionals 中收集 N 个值到一个 ImmutableSet 中”.

其次,如果你需要 Guava 的ImmutableSet,那么你可以使用 Guava Core 附带的合适的 Collector。

使用番石榴的ImmutableSet.toImmutableSet()

自番石榴发布版本21.0(这需要 JDK 8 作为最低版本) 您可以使用 ImmutableSet.toImmutableSet() 返回的 Collector。

@SafeVarargs
private static <T> Set<T> getValues(Supplier<Optional<T>>... suppliers) {

    return Arrays.stream(suppliers)
        .map(Supplier::get)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(ImmutableSet.toImmutableSet());
}

标准 JDK Collectors.toUnmodifiableSet()

为了完整起见,这里有一个不需要依赖项的解决方案。

由于 JDK 中提供了 Java 10 Collector toUnmodifiableSet()。

@SafeVarargs
private static <T> Set<T> getValues(Supplier<Optional<T>>... suppliers) {

    return Arrays.stream(suppliers)
        .map(Supplier::get)
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toUnmodifiableSet());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-10
    • 2021-02-06
    • 2021-10-19
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多