Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Iterating over 2 Lists?

 
Meghna Bhardwaj
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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())
...
 
Meghna Bhardwaj
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats great, thanks... work a charm!

Didn't think it would be so simple.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50251
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and change the assert statement to something like

if(list1.size() != list2.size())
throw new IllegalArgumentException("Two lists of different size passed.");
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic