如何同时迭代两个ArrayLists?

Roh*_*ink 51 java

我有两个数组列表,声明为:

ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Run Code Online (Sandbox Code Playgroud)

这两个字段都包含完全相同的值,它们在自然界中具有实际对应性.

我知道我可以像这样迭代其中一个循环:

for(JRadioButton button: category)
{
     if(button.isSelected())
     {
           buttonName = button.getName();
           System.out.println(buttonName);       
     }
}
Run Code Online (Sandbox Code Playgroud)

但是,我想同时迭代两个LISTS.我知道他们的尺寸完全相同.我怎么做?

Mar*_*oun 94

你可以使用Collection#iterator:

Iterator<JRadioButton> it1 = category.iterator();
Iterator<Integer> it2 = cats_ids.iterator();

while (it1.hasNext() && it2.hasNext()) {
    ...
}
Run Code Online (Sandbox Code Playgroud)


Zol*_*asi 13

如果您经常这样做,您可以考虑使用帮助函数将两个列表压缩成一对列表:

public static <A, B> List<Pair<A, B>> zip(List<A> listA, List<B> listB) {
    if (listA.size() != listB.size()) {
        throw new IllegalArgumentException("Lists must have same size");
    }

    List<Pair<A, B>> pairList = new LinkedList<>();

    for (int index = 0; index < listA.size(); index++) {
        pairList.add(Pair.of(listA.get(index), listB.get(index)));
    }
    return pairList;
}
Run Code Online (Sandbox Code Playgroud)

您还需要一个Pair实现.Apache commons lang包有一个合适的.

有了这些,你现在可以优雅地迭代pairlist:

ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();

for (Pair<JRadioButton, Integer> item : zip(category , cat_ids)) {
   // do something with JRadioButton
   item.getLeft()...
   // do something with Integer
   item.getRight()...
}
Run Code Online (Sandbox Code Playgroud)

  • 不.这就是为什么抛出新的IllegalArgumentException ...行.如果两个列表具有不同的大小,则不明确该做什么:修剪较长的一个,或使用占位符填充较短的列表.因为占位符可以取决于列表的类型,所以最好不要在通用实现中处理. (2认同)

eug*_*e82 13

java8风格:

private static <T1, T2> void iterateSimultaneously(Iterable<T1> c1, Iterable<T2> c2, BiConsumer<T1, T2> consumer) {
    Iterator<T1> i1 = c1.iterator();
    Iterator<T2> i2 = c2.iterator();
    while (i1.hasNext() && i2.hasNext()) {
        consumer.accept(i1.next(), i2.next());
    }
}
//
iterateSimultaneously(category, cay_id, (JRadioButton b, Integer i) -> {
    // do stuff...
});
Run Code Online (Sandbox Code Playgroud)


JRR*_*JRR 11

试试这个

ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
for (int i = 0; i < category.size(); i++) { 
    JRadioButton cat = category.get(i);
    Integer id= cat_ids.get(i);
    ..
}
Run Code Online (Sandbox Code Playgroud)

  • 为了以防万一,我会添加i <category.size()&& i <cat_ids.size() (3认同)