簡體   English   中英

在同一個“for”循環中迭代多個集合?

[英]Iterate through multiple collections in the same "for" loop?

我想知道是否有這樣一種方法來遍歷多個集合,並在 java 中為每個循環擴展。

所以像:

for (Object element : collection1, collection2, ....)
         // do something ...

謝謝

你可以用GuavaIterables.concat()做到這一點:

for (Foo element : Iterables.concat(collection1, collection2)) {
    foo.frob();
}

使用普通的 Java 8 並且沒有任何額外的庫:

public static <T> Iterable<T> compositeIterable(Collection<? extends T>... collections)
{
    Stream<T> compositeStream = Stream.of(collections).flatMap(c-> c.stream());
    return compositeStream::iterator;
}

然后您可以將其用作:

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

}

如果您的列表具有相同的長度,只需使用raw for循環:

Object[] aNum = {1, 2}; 
Object[] aStr = {"1", "2"}; 

for (int i = 0; i < aNum.length; i++) {
    doSomeThing(aNum[i]);
    doSomeThing(aStr[i]);
}

有用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM