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

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

    Use basic loop

    for(int index=0; index < list1.size() ; index++){
      list1.get(index);
      list2.get(index);
    }
    
    0 讨论(0)
  • 2021-01-19 05:09
    int index = 0;
    for(String str1 : list1) {
        str2 = list2.get(index++);
    }
    
    0 讨论(0)
  • 2021-01-19 05:11

    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();) {...} 
    
    0 讨论(0)
  • 2021-01-19 05:12

    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);
        ...
    }
    
    0 讨论(0)
  • 2021-01-19 05:22
    for(int i = 0; i< list1.size(); i++){
      String str1 = list1.get(i);
      String str2 = list2.get(i);
      //do stuff
    }
    
    0 讨论(0)
  • 2021-01-19 05:23

    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.

    0 讨论(0)
提交回复
热议问题