将两个arraylists与迭代器进行比较

时间:2013-01-18 10:41:17

标签: java arraylist iterator while-loop

我需要比较不同大小的两个不同的Arraylists。

我可以用两个循环来完成 - 但我需要使用迭代器。

第二个循环只迭代一次而不是n次。

while (it.hasNext()) {
    String ID = (String) Order.get(i).ID();
    j = 0;              
    while (o.hasNext()) {   
        String Order = (String) Order.get(j).ID();
        if (myOrder.equals(Order)) {
            //do sth
        }
        j++;
        o.next();
    }
    i++;
    it.next();
}

3 个答案:

答案 0 :(得分:3)

您可以以比您更简单的方式使用迭代器:

Iterator<YourThing> firstIt = firstList.iterator();
while (firstIt.hasNext()) {
  String str1 = (String) firstIt.next().ID();
  // recreate iterator for second list
  Iterator<YourThing> secondIt = secondList.iterator();
  while (secondIt.hasNext()) {
    String str2 = (String) secondIt.next().ID();
    if (str1.equals(str2)) {
      //do sth
    }
  }
}

答案 1 :(得分:2)

您需要为o的每次迭代实例化迭代器it,例如

while (it.hasNext()) {
   Iterator<String> o = ...
   while (o.hasNext()) {
     // ...
   }
}

的Nb。你不需要索引变量j。您只需调用o.next()即可获取迭代器引用的列表元素。

答案 2 :(得分:1)

怎么样?
List<String> areInBoth = new ArrayList(list1);
areInBoth.retainAll(list2);
for (String s : areInBoth)
    doSomething();

您需要调整对象的equals方法以比较正确的内容(示例中的ID)。