Thursday, 1 June 2017

Java Collections Tutorial 9: Iterators



Let us create a list of String and then display their contents to the console using a foreach loop.
List<String> list1 = new ArrayList<String>();
list1.add(“root”);
list1.add(“leaves”);
list1.add(“shoot”);
list1.add(“fruit”);
list1.add(“flower”);
for(String item: list1) {
System.out.println(item);
}
Figure 1: Using a foreach loop on a list


The foreach loop is the modern way to iterate through items of the collections class. Prior to Java 5, there was no foreach loop. Instead, Java developers used an object of the type Iterator to iterate through items of the collections framework.
So to create an iterator object for our list, which is list1, we can write that:
Iterator<String> iterator1 = list1.iterator();
Remember that an iterator is a template type, meaning that you have to specify what kinds of objects it is going to point at in the angle brackets. Now, an iterator object has three methods. It has a hasNext() method, which tells you if there is a next item. It has a next() method which returns the next item. Finally, it has a remove() method to remove objects in the list.
An iterator works by pointing each element in a list in turn. So, if we want to get the next element in a list, we can do this:
String partOfPlant = iterator1.next(); 
The above statement will output the first element of the list, which in this case is “root”. If you call next() again, the iterator will now point to and return the next item of the list. It is as if before the first call to next(), the iterator is pointing just before the beginning of the list. So, the main use of the next() method is within a loop. For example, let us create a loop that prints out all the contents of the list:
while (iterator1.hasNext()) {
            String partOfPlant = iterator1.next();
            System.out.println(partOfPlant);
}
Figure 2: Using an iterator


You can use the above loop to also remove items from the list using the remove() method like this:
while (iterator1.hasNext()) {
                                    String partOfPlant = iterator1.next();
                                    if (partOfPlant.equals("flower")) {
                                                iterator1.remove();
                                    }
                        }
                        System.out.println(list1);
Figure 3: iterating through a list while removing items from the list


This is why iterators are still important, even with the introduction of the foreach loop as from Java 5. Iterators help when removing items, pointing to the next item and even checking whether the list has another element. If you try to iterate through the list using a foreach loop and at the same time try to remove an element, you get a ConcurrentModificationException as shown below:
for (String partOfPlant : list1) {
            System.out.println(partOfPlant);
            partOfPlant.remove (1);
}
Figure 4: You cannot use a foreach loop to iterate through a list while modifying the list


However, you can use an iterator to remove an item from the list while iterating through it. 
If you want to add items to a list while concurrently iterating through it, use a ListIterator instead of an Iterator. ListIterator has an add(), hasNext(), hasPrevious(), next(), nextIndex(), previous(), previousIndex(), remove(). You can add an item while iterating like:
If you have any question, please leave it in the comments section below and I will make sure to answer it.
Until next time, take care. 

No comments:

Post a Comment