I'm new to Java. I want to know what an Iterator actually does and when I can use one. Some days ago I used an Iterator to show Hashmap data, but I'm not sure how it works.
-
you should have referred java doc – Ravi Feb 04 '18 at 11:26
-
Time to do [some reading](https://en.wikipedia.org/wiki/Iterator_pattern). – Boris the Spider Feb 04 '18 at 11:26
-
Just look at the documentation and play around with it. There is a lot of examples on the internet. – RoadRunner Feb 04 '18 at 11:29
-
This is a good question and it's not equivalent to "What are the benefits of using an iterator in Java". It should be reopened. – JohnK Nov 04 '20 at 16:09
1 Answers
As you saw when you used it, Iterator will allow you to examine a sequence of data, one piece of data at a time. Iterators are used in enhanced for loops. Below are two for loop styles; the second style implicitly uses these.
final List<String> animals = new ArrayList<String>();
animals.add("Rhino");
for (int i = 0; i < list.size(); i++) {
// Do stuff
}
for (String data : list) {
// Do stuff
}
Though the latter style does not show it, the for loop's header is more like the following.
final Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String creature = iter.next();
// Do stuff
}
On its own, Iterator is an interface and has two methods to implement when one needs to write their own for a data structure: boolean hasNext() and String next(). Their use is shown in the previous example.
In addition, there is one more method that you don't actually have to implement: void remove(). If implemented, the iterator is then capable of removing an item in the data structure mid-iteration, as shown below.
final List<String> animals = new ArrayList<>();
animals.add("Kangaroo");
animals.add("Manatee");
animals.add("Tauntaun");
for (final String creature : animals) {
System.out.println(creature);
}
System.out.println();
final Iterator<String> iter = animals.iterator();
while (iter.hasNext()) {
final String creature = iter.next();
if (creature.equals("Manatee")) {
iter.remove();
}
}
for (final String creature : animals) {
System.out.println(creature);
}
System.out.println();
This is the console if you run the code above.
Kangaroo
Manatee
Tauntaun
Kangaroo
Tauntaun
In terms of implementing an Iterator, the basic idea is to keep track of your place in the sequence of data you're iterating through, like what the first version of the for loop does in the very first code block at the top. The Iterator is essentially doing what that first for loop does but with less to type when one needs to examine sequences of data - which I imagine in general happens quite often. For more on this, you may find it more helpful to read the Iterator documentation.

- 84
- 1
- 5