Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through multiple collections in the same "for" loop?

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

like image 605
One Two Three Avatar asked Mar 30 '12 19:03

One Two Three


People also ask

How do I iterate through collections?

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.

Can you loop through two lists at once Python?

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.

Which loop is used to iterate through collections like arrays without knowing the size of the collection?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).


3 Answers

You can do exactly this with Guava's Iterables.concat():

for (Foo element : Iterables.concat(collection1, collection2)) {
    foo.frob();
}
like image 97
Matt Ball Avatar answered Oct 20 '22 17:10

Matt Ball


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();
}
like image 35
ZzetT Avatar answered Oct 20 '22 16:10

ZzetT


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)
{

}
like image 2
Eng.Fouad Avatar answered Oct 20 '22 16:10

Eng.Fouad