I wonder if there\'s such a way to iterate thru multiple collections with the extended for each loop in java.
So something like:
for (Object element
You can do exactly this with Guava's Iterables.concat():
for (Foo element : Iterables.concat(collection1, collection2)) {
foo.frob();
}
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();
}
Collection<Foo> collection1 = ...
Collection<Foo> collection2 = ...
Collection<Foo> collection3 = ...
...
Collection<Foo> all = ...
all.addAll(collection1);
all.addAll(collection2);
all.addAll(collection3);
...
for(Foo element : all)
{
}
If your lists have the same length, just use the raw for loop:
Object[] aNum = {1, 2};
Object[] aStr = {"1", "2"};
for (int i = 0; i < aNum.length; i++) {
doSomeThing(aNum[i]);
doSomeThing(aStr[i]);
}
It works!