https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
There are 5 ways you can iterate through List.
For Loop
Advanced For Loop
Iterator
While Loop
Collections’s stream() util (Java8)
https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
Here is a common mistake people make when they are trying to do nested iteration over two collections:
List suits = ...; List ranks = ...; List sortedDeck = new ArrayList(); // BROKEN - throws NoSuchElementException! for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(i.next(), j.next()));
Can you spot the bug? Don't feel bad if you can't. Many expert programmers have made this mistake at one time or another. The problem is that the
next
method is being called too many times on the "outer" collection (suits
). It is being called in the inner loop for both the outer and inner collections, which is wrong. In order to fix it, you have to add a variable in the scope of the outer loop to hold the suit:// Fixed, though a bit ugly for (Iterator i = suits.iterator(); i.hasNext(); ) { Suit suit = (Suit) i.next(); for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(suit, j.next()));