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?
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.
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.
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.
The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With