Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 773
JackWM Avatar asked Apr 22 '13 18:04

JackWM


People also ask

How many ways can you traverse a list in Java?

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.


3 Answers

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();) {...} 
like image 114
Maroun Avatar answered Nov 04 '22 20:11

Maroun


for(int i = 0; i< list1.size(); i++){
  String str1 = list1.get(i);
  String str2 = list2.get(i);
  //do stuff
}
like image 30
Simulant Avatar answered Nov 04 '22 22:11

Simulant


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);
    ...
}
like image 30
rgettman Avatar answered Nov 04 '22 20:11

rgettman