如果您坚持使用 Guava 20.0,如何用替代品替换 Guava 的 ImmutableSet.toImmutableSet() 收集器?

How to replace Guava's ImmutableSet.toImmutableSet() collector with an alternative, if you're stuck with using Guava 20.0?

我遇到了一些需要大量工作才能解决的 Guava 依赖性问题。由于第三方库也依赖于 Guava,(不幸的是我不得不使用它),我不得不将我对 Guava 的依赖从 27.0.1-jre 一直降级到 20.0。似乎除了以下代码现在被破坏之外没有主要的副作用,因为 ImmutableSet.toImmutableSet() 仅在 Guava 21.0:

中引入
ImmutableSet.toImmutableSet();

完整的代码块是:

cronJobDefinitions = cronJobsRegistry.get()
                                     .stream()
                                     .map(ThrowingFunction.unchecked(clazz -> clazz.newInstance()
                                                                                   .getCronJobDefinition()))
                                     .collect(ImmutableSet.toImmutableSet());

是否有一种简单的方法可以将 ImmutableSet.toImmutableSet() 替换为 JDK 中的替代项?我目前正在使用 JDK8,(但很想知道,如果更新的 JDK-s 中有更好的解决方案)。

您可以使用 Collectors.toSet 将其收集为一组。但是不能保证返回的 Set 的类型。因此,您可以使用 Collectors.collectingAndThen 将上述集合转换为 Google Guava ImmutableSet.

cronJobDefinitions = cronJobsRegistry.get()
    .stream()
    .map(..)
    .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));