使用 Guava 连接 ImmutableSet
Concatenate ImmutableSet using Guava
我已经习惯了 C#,我们有 IEnumerable<T>.SelectMany
,但发现自己使用 Google 的 Guava 库涉猎了一些 Java 代码。 Guava 中有 SelectMany 的等价物吗?
示例:
如果我有这样的 stream/map 构造
collections
.stream()
.map(collection -> loadKeys(collection.getTenant(), collection.getGroup()))
.collect(GuavaCollectors.immutableSet());
其中 loadKeys
return 类似于 ImmutableSet<String>
,此函数会 return ImmutableSet<ImmutableSet<String>>
但我只想将它们拼合成一个 ImmutableSet<String>
最好的方法是什么?
您可以使用Stream::flatMap
方法:
collections
.stream()
.flatMap(collection -> loadKeys(collection.getTenant(), collection.getGroup()).stream())
.collect(ImmutableSet.toImmutableSet());
请注意,您从 loadKeys
方法结果中得到了 stream
。结果应该是 ImmutableSet<String>
假设 loadKeys
returns 一个集合。
我已经习惯了 C#,我们有 IEnumerable<T>.SelectMany
,但发现自己使用 Google 的 Guava 库涉猎了一些 Java 代码。 Guava 中有 SelectMany 的等价物吗?
示例: 如果我有这样的 stream/map 构造
collections
.stream()
.map(collection -> loadKeys(collection.getTenant(), collection.getGroup()))
.collect(GuavaCollectors.immutableSet());
其中 loadKeys
return 类似于 ImmutableSet<String>
,此函数会 return ImmutableSet<ImmutableSet<String>>
但我只想将它们拼合成一个 ImmutableSet<String>
最好的方法是什么?
您可以使用Stream::flatMap
方法:
collections
.stream()
.flatMap(collection -> loadKeys(collection.getTenant(), collection.getGroup()).stream())
.collect(ImmutableSet.toImmutableSet());
请注意,您从 loadKeys
方法结果中得到了 stream
。结果应该是 ImmutableSet<String>
假设 loadKeys
returns 一个集合。