Java Iterator Interface

The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a subinterface ListIterator.

The Listiterator interface extends the Java Iterator interface.

All the Java collections include an iterator() method. This method returns an instance of iterator used to iterate over elements of collections.


Methods of Iterator

The Iterator interface provides 4 methods that can be used to perform various operations on elements of collections.

  • hasNext() - returns true if there exists an element in the collection
  • next() - returns the next element of the collection
  • remove() - removes the last element returned by the next()
  • forEachRemaining() - performs the specified action for each remaining element of the collection

Example: Implementation of Iterator

In the example below, we have implemented the hasNext(), next(), remove() and forEachRemining() methods of the Iterator interface in an array list.

Output

ArrayList: [1, 3, 2]
Acessed Element: 1
Removed Element: 1
Updated ArrayList: 3, 2,

In the above example, notice the statement:

iterate.forEachRemaining((value) -> System.put.print(value + ", "));

Here, we have passed the lambda expression as an argument of the forEachRemaining() method.

Now the method will print all the remaining elements of the array list.