Implementation of a complex Java Iterator

In a lot of situations it is better to handle data as streams to keep the memory profile low and to decrease latency. To access data in such an environment, it is often useful to use iterators which collect data out of a stream and group them into objects and let the application use the stream like a collection of objects.

There are situations where it is not easy to implement a Java iterator with keeping the contract. Imagine a situation where a complex XML file is coming in via an InputStream and only a part of the XML file is to be parsed and aggregated into a dedicated Object. In this case keeping the contract is not so easy, because keeping hasNext() and next() in sync is complicated…

For this situation, I use a simple design:

The main advantage is the fixed implementation of hasNext() and next(), which is not to be changed anymore. Additionally, the whole logic to check for the next enty and to created if present was moved into a single method, so that there is no mismatch anymore between hasNext() and next(),

Another advantage can be that, there is also now the possibility to peek for the next entry:

Or a little bit more restrictive:

 

Schreibe einen Kommentar