File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Iterating over 2 Lists? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Iterating over 2 Lists?" Watch "Iterating over 2 Lists?" New topic

Iterating over 2 Lists?

Meghna Bhardwaj
Ranch Hand

Joined: Jun 08, 2007
Posts: 109
Hi All,

I have a question about iterating over 2 Lists simultaneoulsy.
My Lists are of the same size and both Lists contain Maps (i.e. Lists of Mapped Objects.) The objects in the lists are different, i.e.
List<Rec1> and List<Rec2> where both Rec1 and Rec2 are mapped objects.

I need to iterate over these 2 lists and compare contents. It is possible to do so, if I had the same object types in both Lists. It can be done as follows: (Seen on

public Integer dotproduct(List<Integer> x, List<Integer> v) {
assert (x.size() == v.size());
int product = 0;
for(Iterator<Integer> x_it = x.iterator(), v_it = v.iterator();
x_it.hasNext() && v_it.hasNext();
product += *
; // no body
return product;

However, my problem is that I have different objects in the Lists!
Any ideas??

Thanks in advance.
[ December 12, 2007: Message edited by: Meghna Bhardwaj ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Just declare the iterators before the loop:

Iterator<Integer> x_it = x.iterator();
Iterator<Double> v_it = v.iterator();
for(;x_it.hasNext() && v_it.hasNext(); product += *

[Jess in Action][AskingGoodQuestions]
Meghna Bhardwaj
Ranch Hand

Joined: Jun 08, 2007
Posts: 109
Thats great, thanks... work a charm!

Didn't think it would be so simple.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46412
. . . and change the assert statement to something like

if(list1.size() != list2.size())
throw new IllegalArgumentException("Two lists of different size passed.");
I agree. Here's the link:
subject: Iterating over 2 Lists?
It's not a secret anymore!