• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Iterating over 2 Lists?

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thats great, thanks... work a charm!

Didn't think it would be so simple.
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.");
 
reply
    Bookmark Topic Watch Topic
  • New Topic