How to Use the Java Iterator in Collections?
In Java, an iterator is an interface and is implemented by all collection classes. The Java collections framework is a group of classes and interfaces that implement reusable collection of data structures. The iterator method returns an object that implements the Iterator interface. An object of an iterator interface can be used to traverse through all elements of a collection. Elements can also be modified and removed from the collection while traversal.
Learn how to code in Java through a beginner’s course at Udemy.com
Characteristics of a Java Iterator:
- It works similar to enumeration.
- The iterator interface is in the Java Collections Framework.
- The Iterator object traverses through all elements of the collection.
- All collection framework Interfaces have the iterator() method.
- Its main difference from other iterators (such as C++ iterator) is that is does not require incrementing an array index to traverse through the elements. It uses the next() method to look up an element and the loop automatically advances after that.
How to Use Java Iterator in Your Java Code?
An iterator must first be obtained before it can be used for traversing. Each class in the collections framework includes an iterator() method that returns an object of the iterator interface. This method can be invoked to obtain an iterator object before traversing the collection. The object can provide you access to each element of the collection. Using an iterator object typically requires going through the following cycle:
- Call the collection’s iterator() method
- Create a loop that calls the hasNext() — which returns a boolean variable. If the returned variable is true, the iterator object accesses the collection; otherwise the looping stops.
- Call the next() method to obtain each item of the collection.
Important Methods Used by the Java Iterator:
1) boolean hasNext(): this method returns true when there is another element to be traversed in the collection.
2) Object next(): It provides the next object to be traversed. This method throws an exception if there are no more elements to be visited in the collection.
How to use the java iterator hasNext() and next() methods?
Every element in the collection can be visited one by one by calling next(). The method throws an exception when there are no more elements in the collection. In order to avoid the exception, you should call hasnext() before next(); this is to make sure the iterator advances only if the next element/object exist in the collection.
For example:
ArrayList arl = new ArrayList(); // declare an arraylist. Iterator itor = arl.iterator(); //Create an Iterator object and call the iterator method //before traversing the collection. while(itor.hasNext()) // checks if there is an element to be visited. { Object obj = itor.next(); // the next element obtained is assigned to obj. The loop // is advanced and it keeps iterating until hasNext returns // false. // some code }
New to Java Collections Framework? Learn it through a course at Udemy
Object remove(): This method removes and returns the last object that was visited. If the objects in the collection have been modified since the last visited object, an IllegalStateException is thrown by the method.
Using the Java Iterator remove() Method
The remove() when called, eliminates the element that was returned by the call to next(). The remove method was added to java iterator because the iterator knows the exact position of all the elements in the collection. It is a lot easier to remove an object from the collection if you know where it is.
The following example code removes the first element in a collection:
ArrayList abc = new ArrayList(); // create an arraylist abc Iterator itr = abc.iterator(); itr.next(); // skip over the first element itr.remove; // remove the first element
Removing adjacent objects:
itr.remove(); itr.next(); itr.remove();
Using the Java Iterator and ArrayList:
import java.util.*; class iteratorDemo { public static void main(String[] arg) { List demoList = new ArrayList(); // create new list String demoArray[] = {“john”, “bob”, “anne”, “stella”, “fred”}; for(int i=0; i<demoArray.length;i++) { demoList.add(demoArray[i]); // add elements to list } Iterator itr = demoList.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); }}}
OUTPUT:
john
bob
anne
stella
fred
In the above example, the iterator method of the List interface is called. It performs simple iteration and checking — check if there is a next element to visit — and displays all elements in an Arraylist.
Using the Java Iterator and ListIterator:
import java.util.*; class CityNames { public static void main (String[] arg) { ArrayList locations = new ArrayList(); // create new array list locations.add(“New York”); //adding elements to array list locations.add(“Tokyo”); locations.add(“Mumbai”); locations.add(“Paris”); System.out.println(“list of cities: “); Iterator itor = locations.iterator(); while(itor.hasNext()) // check if there is a next element { Object abc = itor.next(); // obtain next element and assign it to variable abc System.out.println( abc ); // print location name } System.out.println(“ “); // the following codes modify the elements in the arraylist using ListIterator ListIterator listitr = locations.listIterator(); while(listitr.hasNext()) { Object abc = listlitr.next(); listlitr.set(abc + “ City”); } System.out.print(“Modified list of locations:”); itor = locations.iterator(); while(itor.hasNext()) { Object abc = itor.next(); System.out.println(abc); }}
OUTPUT:
List of cities:
New York
Tokyo
Mumbai
Paris
Modifies list of locations:
New York City
Tokyo City
Mumbai City
Paris City
The list of elements can be displayed in reverse order using the hasPrevious() and previous() of the ListIterator interface.
Important points about Java Iterators:
1) Although traversal actions can be achieved using the common looping structures such as a for or while loop, using an iterator has a few advantages
- It will allow you to scan forward through any collection.
- If you remove elements from an array using a traditional looping structure, you will encounter an IndexOutofBoundsException. This is because the size of the array changes as you iterate through it and you may have set the size of the array before the iteration. That problem does not exist with iterators because the hasnext() and next() does not rely on a pre-defined index.
2) For collections that implement the List interface, you can also obtain an iterator by calling the ListIterator. The list iterator allows you to access the objects in the collection in either forwards or backward direction; it also lets you modify an element.
Learn about various Java classes and interfaces through a course at udemy.com
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.