wood burning stoves 2.0*
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

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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 http://today.java.net/pub/a/today/2006/11/07/nuances-of-java-5-for-each-loop.html)

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 += x_it.next() * v_it.next())
; // 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: 24183

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 += x_it.next() * v_it.next())

[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: 38441
. . . 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: http://aspose.com/file-tools
subject: Iterating over 2 Lists?