60

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

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

这两个字段都包含完全相同的相同数量的值,它们在自然中实际上是对应的。

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

for(JRadioButton button: category)
{
     if(button.isSelected())
     {
           buttonName = button.getName();
           System.out.println(buttonName);       
     }
}

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

4

6 回答 6

114

您可以使用Collection#iterator

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

while (it1.hasNext() && it2.hasNext()) {
    ...
}
于 2013-04-13T07:19:09.970 回答
19

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...
});
于 2016-06-03T10:41:31.220 回答
16

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

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;
}

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

有了这些,您现在可以优雅地迭代配对列表:

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()...
}
于 2014-07-04T08:36:42.810 回答
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);
    ..
}
于 2013-04-13T07:13:10.163 回答
1

尽管您希望两种尺寸相同,但为了更安全,请获取它们的尺寸并确保它们相等。

设该尺寸值为count。然后使用通用 for 循环,迭代直到计数并将值作为数组索引访问。如果 'i' 是索引,则在 for 循环中进行如下访问。

category[i] and cat_ids[i] 

category[i].isSelected()等等

于 2013-04-13T07:25:12.313 回答
1
ArrayList<JRadioButton> category = new ArrayList<JRadioButton>();
ArrayList<Integer> cat_ids = new ArrayList<Integer>();
Iterator<JRadioButton> itrJRB = category.iterator();
Iterator<Integer> itrInteger = cat_ids.iterator();
while(itrJRB.hasNext() && itrInteger.hasNext()) {
    // put your logic here
}
于 2013-04-13T07:34:40.327 回答