Rohitink Rohitink - 6 months ago 40
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)
{
if(button.isSelected())
{
buttonName = button.getName();
System.out.println(buttonName);
}
}


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

You can use Collection#iterator:

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

while (it1.hasNext() && it2.hasNext()) {
    ...
}