Iterate through multiple collections in the same “for” loop?

前端 未结 4 1308

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          


        
相关标签:
4条回答
  • 2020-12-17 10:55

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

    for (Foo element : Iterables.concat(collection1, collection2)) {
        foo.frob();
    }
    
    0 讨论(0)
  • 2020-12-17 10:55

    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();
    }
    
    0 讨论(0)
  • 2020-12-17 11:08
    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)
    {
    
    }
    
    0 讨论(0)
  • 2020-12-17 11:15

    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!

    0 讨论(0)
提交回复
热议问题