How to Iterate through two ArrayLists Simultaneously? [duplicate]
You can use Collection#iterator
:
Iterator<JRadioButton> it1 = category.iterator();
Iterator<Integer> it2 = cats_ids.iterator();
while (it1.hasNext() && it2.hasNext()) {
...
}
java8 style:
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...
});
If you do this often you may consider using a helper function to zip two lists into one pair list:
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;
}
You will also need a Pair implementation. Apache commons lang package has a proper one.
And with these you can now elegantly iterate on the 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()...
}
Try this
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);
..
}
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
}