Rohitink Rohitink - 1 year ago 162
Java Question

How to Iterate through two ArrayLists Simultaneously?

I Have Two Array Lists, Declared as:

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

Both of the these fields contain exactly, the Same No of Values, which are infact corresponding in Nature.

I know I can iterate over one of the loops like this:

for(JRadioButton button: category)
buttonName = button.getName();

But, I would like to iterate over both the LISTS simultaneously. I know they have the exact same size. How do I Do that?

Answer Source

You can use Collection#iterator:

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

while (it1.hasNext() && it2.hasNext()) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download