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 : collection1, collection2, ....)
// do something ...
Thanks
There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write.
Example 2: Using itertools (Python 2+)Using the zip_longest() method of itertools module, you can iterate through two parallel lists at the same time. The method lets the loop run until the longest list stops.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With