If you are a newbie to Java or even an experienced programmer, you may face a situation where you need to transverse through all the elements of a collection, display the elements one by one, or even retrieve each of the elements. This is where your knowledge of iterators will be at the test.
What is the difference between using iterators rather than using the for-loop and the while loop? Both of these can be used to transverse through a collection of elements, but if you need to remove some of the elements from a collection during iteration, then loops cannot be applied.
By iteration, we mean traversing through elements one by one. This involves elements of a collection such as LinkedList, ArrayList, HashMap e.t.c. Iterators are applicable when one wants to search for a particular element in a collection, display the elements one by one, access data elements in a collection, and remove specific data elements from the collection.
It’s not possible to reverse the order of iteration. Iterators iterate over a collection in forwarding order, and they implement java. util.Iterator interface. With that said, we can conclude that an iterator belongs to the Java Collection framework.
Declaration of an Iterator
Iterator iterator_name = name_of_collection.iterator();
eg.
Iterator<Integer> numbers = values.iterator();
Methods used by Iterators
- Void remove () – = this method is used to removes the current element to which the iterator is pointing. If you call the method remove() without invoking the next() method, an IllegalStateException is thrown.
- Object Next () = this method returns the next element. If there is no next element, NoSuchElementException is thrown.
- Boolean hasNext() = = this method returns true in a scenario where we have next element, or else, returns false.
Example:
package iterator; import java.util.ArrayList; import java.util.Iterator; public class Iterator { public static void main(String[] args) { ArrayList<Integer> values = new ArrayList<Integer>(); values.add(10); values.add(20); values.add(30); values.add(40); values.add(50); values.add(60); values.add(70); values.add(80); values.add(90); Iterator<Integer> numbers = values.iterator(); while (numbers.hasNext()) { int number = numbers.next(); System.out.print(number + " "); if (number == 30) numbers.remove(); } System.out.println("\n================"); numbers = values.iterator(); while (numbers.hasNext()) { int number = numbers.next(); System.out.print(number + " "); } } }
Output:
run:
10 20 30 40 50 60 70 80 90
================
10 20 40 50 60 70 80 90 BUILD SUCCESSFUL (total time: 0 seconds)
From the above example, we have applied all the three methods of an Iterator: next( ), remove( ) and hasNext( ). We have used two while loops. The first while loop prints all the elements up to a point where the iterator has no next element. It also removes ’30’ from the ArrayList. The second while loop prints the values of the ArrayList after removing element 30.
Important features of Iterators in Java
- Enables traversing elements of a collection
- Allow accessing elements of a collection
- Enables display of elements one by one in a collection
- Allows removal of an element in a collection while accessing it
- Allows forward direction access of elements in a collection
Examples of Iterators in java
List Iterator
This is an iterator that transverses over a list. It’s only applicable for classes like the Array List and the LinkedList.A list iterator enables bi-directional transversing. It uses its methods ‘hasNext ( )’ and ‘next ( )’ for iteration.
package iterator; import java.util.ArrayList; import java.util.ArrayList; import java.util.List; public class Iterator { public static void main(String[] args) { // create a list List<String> cars = new ArrayList<String>(); // add elements cars.add("Toyota"); cars.add("Benz"); cars.add("Mercidez"); cars.add("Noah"); cars.add("Corolla"); // get iterator over the list java.util.Iterator<String> iterator = cars.iterator(); // iterate over the list while (iterator.hasNext()) { // get current element String element = iterator.next(); System.out.println(element); } } }
Output:
run:
Toyota
Benz
Mercidez
Noah
Corolla
BUILD SUCCESSFUL (total time: 0 seconds)
From the above example, we started by creating a list of cars. Added elements to the list using the ‘add( )’ method. To iterate through the list, we created an iterator. Used the hasNext ( ) and next ( ) methods to iterate through and display the list elements.
Set Iterator
We can also perform an iteration over a set. In java, we refer to a set as a collection that does not contain duplicate elements.Java has three general-purpose set implementations, which include; HashSet, LinkedHashSet, and TreeSet. In the below example, we will look at traversing through HashSet, which stores its elements in a hash table.
package iterator; import java.util.HashSet; //import java.util.Iterator; import java.util.Set; public class Iterator { public static void main(String[] args) { // create a set Set<String> cars = new HashSet<String>(); // add elements to he set cars.add("Toyota"); cars.add("Benz"); cars.add("Mercidez"); cars.add("Noah"); cars.add("Corolla"); // get iterator over the set Iterator<String> iterator = cars.iterator(); // iterate over the set while (iterator.hasNext()) { // get current element String element = iterator.next(); System.out.println(element); } } }
Output:
run:
Toyota
Mercidez
Benz
Noah
Corolla
BUILD SUCCESSFUL (total time: 0 seconds)
Map Iterator
A map in java is an object that maps keys to values. For a Map, we cannot iterate directly. Instead, we will iterate over its set of values as shown below.
package iterator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Iterator { public static void main(String[] args) { // create a hashmp Map<Integer, String> cars = new HashMap<Integer, String>(); // add elements to the map cars.put(1, "Toyota"); cars.put(2, "Benz"); cars.put(3, "Mercidez"); cars.put(4, "Noah"); cars.put(5, "Corolla"); // get iterator over map values Iterator<Integer> iterator = cars.keySet().iterator(); // iterate over the set while (iterator.hasNext()) { // get current element Integer key = iterator.next(); System.out.println("value:" + cars.get(key)); } } }
Output:
run:
value:Toyota
value:Benz
value:Mercidez
value:Noah
value:Corolla
BUILD SUCCESSFUL (total time: 0 seconds)
From the above example, we are traversing through the Map using its set of keys. Each key is mapping to at most one value.
Advantages of java Iterator
- Can be used in any collection class
- It supports the READ and REMOVE operations
- Its easy-to-use method names
Disadvantages of java Iterator
- It does not support CREATE and Update operations
- Does not support reverse order but forward direction only
Types of Iterators
We can also categorize iterators in two ways: fail-fast iterator and fail-safe iterator.
- Fail-fast iterator – This type of iterator fails once the structure of a collection changes since looping has begun. By this, change means; accessing, adding, updating, or removing elements of a collection.
- Fail-safe iterator – this type of iterator does not throw any exception in case of any modification at the time of traversing. It works on a copy of the collection rather than the original collection.
Conclusion
In this tutorial, we have covered iterator in java. To use Iterators, you need to import Java.util.* library. This is because an iterator is an interface of the util package. This collection classes include HashMap, ArrayList, LinkedList, etc. With an iterator, you can modify these collection classes while traversing. Iterators are also designed to change collections easily they loop over. The ‘next( )’ method returns the next element, the hasNext ( ) method returns true is we have next element else returns false and the remove ( ) method removes elements from a collection while looping.