java 在番石榴中展平一个 Iterable<Iterable<T>>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5949091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flattening an Iterable<Iterable<T>> in Guava
提问by Andy Whitfield
Is there a flatten
method in Guava - or an easy way to convert an Iterable<Iterable<T>>
to an Iterable<T>
?
flatten
Guava 中是否有一种方法 - 或者将 an 转换Iterable<Iterable<T>>
为 an的简单方法Iterable<T>
?
I have a Multimap<K, V>
[sourceMultimap] and I want to return all values where the key matches some predicate [keyPredicate]. So at the moment I have:
我有一个Multimap<K, V>
[sourceMultimap],我想返回键匹配某个谓词 [keyPredicate] 的所有值。所以目前我有:
Iterable<Collection<V>> vals = Maps.filterKeys(sourceMultimap.asMap(), keyPredicate).values();
Collection<V> retColl = ...;
for (Collection<V> vs : vals) retColl.addAll(vs);
return retColl;
I've looked through the Guava docs, but nothing jumped out. I am just checking I've not missed anything. Otherwise, I'll extract my three lines into a short flatten generic method and leave it as that.
我已经浏览了番石榴文档,但没有任何内容跳出来。我只是在检查我没有错过任何东西。否则,我会将我的三行提取到一个简短的展平通用方法中并保持原样。
回答by Sean Parsons
The Iterables.concat methodsatisfies that requirement:
该Iterables.concat方法满足了这一要求:
public static <T> Iterable<T> concat(Iterable<? extends Iterable<? extends T>> inputs)
回答by Jeffrey Bosboom
As of Java 8, you can do this without Guava. It's a bit clunky because Iterable doesn't directly provide streams, requiring the use of StreamSupport, but it doesn't require creating a new collection like the code in the question.
从 Java 8 开始,您可以在没有 Guava 的情况下执行此操作。这有点笨拙,因为Iterable 不直接提供流,需要使用 StreamSupport,但它不需要像问题中的代码那样创建新的集合。
private static <T> Iterable<T> concat(Iterable<? extends Iterable<T>> foo) {
return () -> StreamSupport.stream(foo.spliterator(), false)
.flatMap(i -> StreamSupport.stream(i.spliterator(), false))
.iterator();
}