Iterate through multiple collections in the same "for" loop?
With plain Java 8 and without any additional libraries:
public static <T> Iterable<T> compositeIterable(Collection<? extends T>... collections)
{
Stream<T> compositeStream = Stream.of(collections).flatMap(c-> c.stream());
return compositeStream::iterator;
}
Then you can use it as:
for (Foo element : MyClass.compositeIterable(collection1, collection2)) {
foo.frob();
}
You can do exactly this with Guava's Iterables.concat()
:
for (Foo element : Iterables.concat(collection1, collection2)) {
foo.frob();
}