Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Iterate through two ArrayLists Simultaneously? [duplicate]

Tags:

java

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?

like image 739
Rohitink Avatar asked Apr 13 '13 07:04

Rohitink


People also ask

How do you iterate over two or more lists at the same time?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.

Can you combine ArrayLists?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

How do you compare two ArrayLists are equal?

The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.

DO FOR EACH loops work for ArrayLists?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .


2 Answers

You can use Collection#iterator:

Iterator<JRadioButton> it1 = category.iterator(); Iterator<Integer> it2 = cats_ids.iterator();  while (it1.hasNext() && it2.hasNext()) {     ... } 
like image 126
Maroun Avatar answered Sep 29 '22 05:09

Maroun


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... }); 
like image 22
eugene82 Avatar answered Sep 29 '22 04:09

eugene82