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?
I will recommend foreach loop.
Iterator. Java provides an interface Iterator to iterate over the Collections, such as List, Map, etc.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With