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

后端 未结 7 1595
萌比男神i
萌比男神i 2021-01-19 04:55

E.g.

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

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

suppose we are sure that list1.size() equals list2

7条回答
  •  無奈伤痛
    2021-01-19 05:11

    You can use iterators:

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

    Or:

    for(Iterator it1 = ... it2..; it1.hasNext() && it2.hasNext();) {...} 
    

提交回复
热议问题