I've inherited a bunch of code that makes extensive use of parallel arrays to store key/value pairs. It actually made sense to do it this way, but it's sort of awkward to write loops that iterate over these values. I really like the new Java foreach construct, but it does not seem like there is a way to iterate over parallel lists using this.
With a normal for
loop, I can do this easily:
for (int i = 0; i < list1.length; ++i) {
doStuff(list1[i]);
doStuff(list2[i]);
}
But in my opinion this is not semantically pure, since we are not checking the bounds of list2
during iteration. Is there some clever syntax similar to the for-each that I can use with parallel lists?
I would use a
Map
myself. But taking you at your word that a pair of arrays makes sense in your case, how about a utility method that takes your two arrays and returns anIterable
wrapper?Conceptually:
The
Iterable<Pair<K,V>>
wrapper would hide the bounds checking.Simple answer: No.
You want sexy iteration and Java byte code? Check out Scala: Scala for loop over two lists simultaneously
Disclaimer: This is indeed a "use another language" answer. Trust me, I wish Java had sexy parallel iteration, but no one started developing in Java because they want sexy code.