我已經習慣了 C#,IEnumerable<T>.SelectMany但發現自己使用 Google 的 Guava 庫涉足了一些 Java 代碼。番石榴中是否有等同于 SelectMany 的東西?示例:如果我有這樣的流/映射結構collections
.stream()
.map(collection -> loadKeys(collection.getTenant(), collection.getGroup()))
.collect(GuavaCollectors.immutableSet());whereloadKeys返回類似的東西ImmutableSet<String>,這個函數會返回ImmutableSet<ImmutableSet<String>>,但我想把它們壓平成一個ImmutableSet<String>最好的方法是什么?
1 回答

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
您可以使用Stream::flatMap
方法:
collections .stream() .flatMap(collection -> loadKeys(collection.getTenant(), collection.getGroup()).stream()) .collect(ImmutableSet.toImmutableSet());
請注意,您得到了方法stream
外的loadKeys
結果。結果應該ImmutableSet<String>
假設loadKeys
返回一個集合。
添加回答
舉報
0/150
提交
取消