如何同时迭代两个ArrayList?

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

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。 我知道他们有完全相同的大小。 我怎么做?

你可以使用Collection#iterator

 Iterator<JRadioButton> it1 = category.iterator(); Iterator<Integer> it2 = cats_ids.iterator(); while (it1.hasNext() && it2.hasNext()) { ... } 

尝试这个

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

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

 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包有一个适当的。

现在,你可以优雅地重复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()... } 

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

虽然你期望两种尺寸都是一样的,但为了安全起见,要把它们放在一起,确保它们是平等的。

让这个大小的值是count 。 然后使用genericsfor循环,迭代直到count并以数组索引的forms获取值。 如果'我'是索引,然后在for循环中进行如下所示。

 category[i] and cat_ids[i] 

category[i].isSelected()