‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection.
java.util package has public interface Iterator and contains three methods:
- boolean hasNext(): It returns true if Iterator has more element to iterate.
- Object next(): It returns the next element in the collection until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.
- void remove(): It removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to
next()
. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. - forEachRemaining – Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.
Below is an example of use of Iterator. The iterator() method is used to get an iterator for any collection:
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Audi");
cars.add("BMW");
cars.add("Ford");
cars.add("Duster");
// Get the iterator
Iterator<String> it = cars.iterator();
// Print the first item
System.out.println("First element from list :"+it.next());
}
}
Output
First element from list :Audi
Looping through Collection
In the below example, we are looping through the collection using hasNext() and next() methods of Iterator.
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Audi");
cars.add("BMW");
cars.add("Ford");
cars.add("Duster");
// Get the iterator
Iterator<String> iterator = cars.iterator();
System.out.println("List elements : ");
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
System.out.println();
}
}
Output
List elements :
Audi BMW Ford Duster
Removing elements from Collection
Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping. In the below example, I’m deleting the items whose reminder are not 0.
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(20);
numbers.add(8);
numbers.add(10);
numbers.add(50);
// Get the iterator
Iterator<Integer> it = numbers.iterator();
System.out.println("List of Numbers : ");
while (it.hasNext()) {
Integer i = it.next();
if (i / 10 == 0) {
it.remove();
}
}
System.out.println(numbers);
}
}
Output
List of Numbers :
[20, 10, 50]
I hope you are cleared about Iterators now. Enjoy learning. Cheers!!