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

后端 未结 7 1523
萌比男神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:32

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题