Iterating with two iterators

I have two array lists which have a different number of items in them. The first iteration works well, but when it moves on the the next, nothing happens which I suspect is because the second iterator has no next. Is there anyway to reset it?

Iterator<Integer> itID = ID.iterator();
    Iterator<String> itTable = Table.iterator();
    Iterator<String> itColumn = Column.iterator();
    while(itID.hasNext()){
        int i = itID.next();
        System.out.println(i);
        while(itTable.hasNext()){
            String SQL = "select " + itColumn.next() + " from " +  itTable.next() + " where id=" + i;
            System.out.println(SQL);
        }
    }

Answer

I think the problem is that you have to move inside the first cycle the instantiation of the iterators itTable and itColumn.

Iterator<Integer> itID = ID.iterator();
while (itID.hasNext()) {
    // Every time you ask for an iterator, you obtain a new one.
    Iterator<String> itTable = Table.iterator();
    Iterator<String> itColumn = Column.iterator();
    int i = itID.next();
    System.out.println(i);
    while(itTable.hasNext()){
        String SQL = "select " + itColumn.next() + " from " +  itTable.next() + " where id=" + i;
        System.out.println(SQL);
    }
}

So the best way to “reset” an iterator is to ask to the aggregate for a new instance of the iterator itself.

Leave a Reply

Your email address will not be published. Required fields are marked *