stevenpcurtis
stevenpcurtis

Reputation: 2001

Compare two arraylists with iterators

I need to compare two different Arraylists of different sizes.

I can do this with two loops - but I need to use iterators.

The second loop only iterates once instead of n times.

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();
}

Upvotes: 1

Views: 10470

Answers (4)

brimborium
brimborium

Reputation: 9512

You can use iterators in a much simpler way than you do:

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
    }
  }
}

Upvotes: 4

Danstahr
Danstahr

Reputation: 4319

What about

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

You'll need to adjust the equals method of your objects to compare the right stuff (IDs in your example).

Upvotes: 1

stealthjong
stealthjong

Reputation: 11093

Iterator<Object> it = list1.iterator();
while (it.hasNext()) {
    Object object = it.next();
    Iterator<Object> o = list2.iterator();
    while (o.hasNext()) {   
        Object other = o.next();
        if (object.equals(other)) {
            //do sth
        }
    }
}

Two iterators because of two lists, get each object with check for next and getting the next item (hasNext() and next()).

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272337

You need to instantiate the iterator o for each iteration of it e.g.

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

Nb. you don't need the index variable j. You can just call o.next() to get the element of the list referenced by the iterator.

Upvotes: 2

Related Questions