Ways to iterate
There are different ways to iterate a collection in Java: - Foreach loop - Iterator - For Loop - While Loop - Stream API
Use foreach or stream api when possible and make sense
If possible, use foreach loop, or stream api, as they are simplest and less error-prone: no extra state to track. - But don’t use stream.foreach
All other approaches need track more states: - when use Iterator, need call iterator.hasNext(), iterator.next() - when use for loop, need track the index, same for the while loop
Iterator
- Iterator works for all collections
- compared with for loop, list.get(index) would have performance issue for linkedlist.
if(iterator.hasNext())
is less error prone, and easier to read and write compared withif(index == list.size()-1 )
For loop
In the last example, we use iterator to iterate the collection, and also track the index. It would be simpler to use for loop.
int index = 0;
while (valuesListIt.hasNext()) {
values = valuesIt.next();
//....
index++;
// is last element?
if(valuesListIt.hasNext()){
}
}
Similarly, the above code can be simplified to as below: