Flattening an Iterable<Iterable<T>> in Guava

喜欢而已 提交于 2019-12-03 10:22:01
Sean Parsons

The Iterables.concat method satisfies that requirement:

public static <T> Iterable<T> concat(Iterable<? extends Iterable<? extends T>> inputs)

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.

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!