E.g.
for(String str : list1) {
...
}
for(String str : list2) {
...
}
suppose we are sure that list1.size()
equals list2
Use basic loop
for(int index=0; index < list1.size() ; index++){
list1.get(index);
list2.get(index);
}
int index = 0;
for(String str1 : list1) {
str2 = list2.get(index++);
}
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();) {...}
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);
...
}
for(int i = 0; i< list1.size(); i++){
String str1 = list1.get(i);
String str2 = list2.get(i);
//do stuff
}
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.