我习惯了C#,在那里我们有IEnumerable<T>.SelectMany,但我发现自己在使用谷歌的Guava库来涉足一些Java代码。在Guava中有没有等同于SelectMany的东西?
示例:如果我有一个流/映射结构,如下所示
collections
.stream()
.map(collection -> loadKeys(collection.getTenant(), collection.getGroup()))
.collect(GuavaCollectors.immutableSet());当loadKeys返回类似于ImmutableSet<String>的内容时,此函数将返回ImmutableSet<ImmutableSet<String>>,但我只想将它们展平为一个ImmutableSet<String>
那么最好的方法是什么呢?
发布于 2019-07-10 03:37:37
您可以使用Stream::flatMap方法:
collections
.stream()
.flatMap(collection -> loadKeys(collection.getTenant(), collection.getGroup()).stream())
.collect(ImmutableSet.toImmutableSet());请注意,您从loadKeys方法stream中获得了结果。假设loadKeys返回一个Set,那么结果应该是ImmutableSet<String>。
https://stackoverflow.com/questions/56959363
复制相似问题