Nifty way to iterate over parallel arrays in Java using foreach

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 an Iterable wrapper?

Conceptually:

for (Pair<K,V> p : wrap(list1, list2)) {
    doStuff(p.getKey());
    doStuff(p.getValue());
}

The Iterable<Pair<K,V>> wrapper would hide the bounds checking.

Leave a Comment