JackWM
JackWM

Reputation: 10555

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

E.g.

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

Upvotes: 5

Views: 17291

Answers (7)

Sashi
Sashi

Reputation: 2425

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

Upvotes: 0

Goran Belfinger
Goran Belfinger

Reputation: 71

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);
    }
}

Upvotes: 1

Maroun
Maroun

Reputation: 95978

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();) {...} 

Upvotes: 22

Madhusudan Joshi
Madhusudan Joshi

Reputation: 4476

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.

Upvotes: 0

Simulant
Simulant

Reputation: 20122

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

Upvotes: 8

rgettman
rgettman

Reputation: 178293

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);
    ...
}

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240928

Use basic loop

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

Upvotes: 1

Related Questions