supports iterator over all kinds of Collection types (Set, Queue, etc)
can remove elements during iteration. - faster than Tranditional way in case of LinkedList or other Collection implementation where random access is time-consuming.
Cons:
too much code
The Enhanced for way
This is the most recommended way since Java 5 if you just need to iterate over a Collection without the need to access to the index.
1
2
3
4
5
6
7
8
List<Integer>numbers=...// read as "for each number in numbers"for(Integernumber:numbers){if(number%2==0){// do something with number}}
TIP: To iterate over an entirejava.util.Map, please use this:
keep variables’ scopes clean (especially in nested loops)
Cons:
cannot access to the index of the element (well, not every time we need it actually)
The Java 8 way (or the function way or the lambda way)
In Java 8, Stream API has been introduce which makes it very easy to iterate and do somthing no elements of a Collection.
1
2
3
4
5
6
7
8
9
List<Integer>numbers=...numbers.stream().filter(number->numbers%2==0).forEach(number->doSomething(number));// or simplynumbers.forEach(number->doSomething(number));
Pros:
easy to write and read
method chain
lazy evaluate
Cons:
the API has quite a lot of methods so it takes time to master all of them.