Nifty way to iterate over parallel arrays in Java

2020-02-07 17:42发布

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?

8条回答
Evening l夕情丶
2楼-- · 2020-02-07 18:19

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.

查看更多
仙女界的扛把子
3楼-- · 2020-02-07 18:19

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.

查看更多
登录 后发表回答