假设我有2个并行集合,例如:a中的人名List<String>列表以及a List<Int>中相同顺序的年龄列表(以便每个集合中的任何给定索引指向同一个人).
我想同时遍历这两个集合,并获取每个人的姓名和年龄,并用它做一些事情.使用数组,这很容易完成:
for (int i = 0; i < names.length; i++) {
do something with names[i] ....
do something with ages[i].....
}
Run Code Online (Sandbox Code Playgroud)
使用集合执行此操作的最优雅方式(在可读性和速度方面)是什么?
Mar*_*wis 65
it1 = coll1.iterator();
it2 = coll2.iterator();
while(it1.hasNext() && it2.hasNext()) {
value1 = it1.next();
value2 = it2.next();
do something with it1 and it2;
}
Run Code Online (Sandbox Code Playgroud)
当较短的集合耗尽时,此版本终止; 或者,您可以继续,直到较长的一个用尽,设置值1.value2为null.
jee*_*ef3 32
我会创建一个封装两者的新对象.把它扔进数组并迭代它.
List<Person>
Run Code Online (Sandbox Code Playgroud)
哪里
public class Person {
public string name;
public int age;
}
Run Code Online (Sandbox Code Playgroud)
cle*_*tus 10
您可以为它创建一个接口:
public interface ZipIterator<T,U> {
boolean each(T t, U u);
}
public class ZipUtils {
public static <T,U> boolean zip(Collection<T> ct, Collection<U> cu, ZipIterator<T,U> each) {
Iterator<T> it = ct.iterator();
Iterator<U> iu = cu.iterator();
while (it.hasNext() && iu.hasNext()) {
if (!each.each(it.next(), iu.next()) {
return false;
}
}
return !it.hasNext() && !iu.hasNext();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你有:
Collection<String> c1 = ...
Collection<Long> c2 = ...
zip(c1, c2, new ZipIterator<String, Long>() {
public boolean each(String s, Long l) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
for (int i = 0; i < names.length; ++i) {
name = names.get(i);
age = ages.get(i);
// do your stuff
}
Run Code Online (Sandbox Code Playgroud)
这并不重要.你的代码不会得到优雅的分数.只要这样做就可以了.请不要膨胀.