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)
?
Essentially, there are only two ways to iterate over a list: by using an index or by using an iterator. The enhanced for loop is just a syntactic shortcut introduced in Java 5 to avoid the tedium of explicitly defining an iterator.
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);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With