Till Java 7, the collections framework relied on the concept of external iterationThis Iterator is also known as active iterator or explicit iterator. For this type of iterator the control over iteration of elements is with the programmer. Which means that the programmer define when and how the next element of iteration is called.
External Iterator
With external iterators responsibility of iterating over the elements, and making sure that this iteration takes into account the total number of records, whether more records exist to be iterated and so on lies with the programmer.
The iteration concept starting with Enumerations, iterations then moved on to Iterators(remember iterator(), next() or hasNext() methods for iterators). Then came Java 5 and along with came the enhanced for-loop which made use of generics to make iteration a lot easier. Lets see an example of enhanced for-loop introduced in Java 5 which uses the Iterable interface.
Internal Iterator
Internal Iterators manage the iterations in the background. This leaves the programmer to just declaratively code what is meant to be done with the elements of the Collection, rather than managing the iteration and making sure that all the elements are processed one-by-one.
Here follows the internal iteration corresponding to the above example
In the above code, we are just telling the forEach method what to do(i.e. print) with each String in the alphabetList list using a lambda expression
Advantage of Internal Iterators
- Improved code readability as its declarative in nature
- Concise code as multiple lines of code for external iterators is reduced to just one or two lines of code in case of internal iterators
- Simplified implementation/less defects as code written by programmer is very less, chances of bugs creeping into the iteration logic are not there.
Where to use
If you want more control over the iteration, and want to perform some check or operation for a particular index then external iterators are preferred over internal ones.
Its important to understand what role the internal iterator plays in the Java 8 scheme of things. In the previous code example for forEach method, we could have made use of the java 8 Streams API to first create a Stream of elements in the List and then pipeline the stream into a forEach method like this –
alphabetList.stream().forEach(name -> System.out.println(name));//Internal Iteration
The forEach method comes under the category of terminal operations when working with streams i.e. it ends the chain of pipelined operations to produce a result.
No comments:
Post a Comment