Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to most elegantly iterate through parallel collections?

Say I have 2 parallel collections, eg: a list of people's names in a List<String> and a list of their age in a List<Int> in the same order (so that any given index in each collection refers to the same person).

I want to iterate through both collections at the same time and fetch the name and age of each person and do something with it. With arrays this is easily done with:

for (int i = 0; i < names.length; i++) {    do something with names[i] ....    do something with ages[i]..... } 

What would be the most elegant way (in terms of readability and speed) of doing this with collections?

like image 730
tekumara Avatar asked Sep 02 '09 04:09

tekumara


People also ask

Which loop is best to work with collection?

I will recommend foreach loop.

Which class is used to iterate through a collection?

Iterator. Java provides an interface Iterator to iterate over the Collections, such as List, Map, etc.


2 Answers

I would create a new object that encapsulates the two. Throw that in the array and iterate over that.

List<Person> 

Where

public class Person {     public string name;     public int age; } 
like image 29
jeef3 Avatar answered Sep 20 '22 02:09

jeef3


it1 = coll1.iterator(); it2 = coll2.iterator(); while(it1.hasNext() && it2.hasNext()) {    value1 = it1.next();    value2 = it2.next();    do something with it1 and it2; } 

This version terminates when the shorter collection is exhausted; alternatively, you could continue until the longer one is exhausted, setting value1 resp. value2 to null.

like image 118
Martin v. Löwis Avatar answered Sep 21 '22 02:09

Martin v. Löwis