简体   繁体   中英

In Java, how to traverse two lists at the same time?

Eg

for(String str : list1) {
...
}

for(String str : list2) {
...
}

suppose we are sure that list1.size() equals list2.size() , how to traverse these two lists in one for statement?

Maybe something like for(String str1 : list1, str2 : list2) ?

You can use iterators :

Iterator<String> it1 = list1.iterator();
Iterator<String> it2 = list2.iterator();
while(it1.hasNext() && it2.hasNext()) { .. }

Or:

for(Iterator<String> it1 = ... it2..; it1.hasNext() && it2.hasNext();) {...} 
for(int i = 0; i< list1.size(); i++){
  String str1 = list1.get(i);
  String str2 = list2.get(i);
  //do stuff
}

You can't traverse two lists at the same time with the enhanced for loop; you'll have to iterate through it with a traditional for loop:

for (int i = 0; i < list1.size(); i++)
{
    String str1 = list1.get(i);
    String str2 = list2.get(i);
    ...
}

Use basic loop

for(int index=0; index < list1.size() ; index++){
  list1.get(index);
  list2.get(index);
}

In case someone is interested, this is the solution that will iterate fully thru both lists even if they are not of the same size.

int max = Math.max(list1.size(), list2.size());
for(int i=0; i<max; ++i){
    if(list1.size()<i){
        list1.get(i);
    }
    if(list2.size()<i){
        list2.get(i);
    }
}

As you say that both the list are of same size, then you can use "for" loop instead of "for-each" loop. You can use get(int index) method of list to get the value during each iteration.

int index = 0;
for(String str1 : list1) {
    str2 = list2.get(index++);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM