In this tutorial, we will learn about the Java Iterator interface with the help of an example.

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

Iterator - 图1

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.

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3. class Main {
  4. public static void main(String[] args) {
  5. // Creating an ArrayList
  6. ArrayList<Integer> numbers = new ArrayList<>();
  7. numbers.add(1);
  8. numbers.add(3);
  9. numbers.add(2);
  10. System.out.println("ArrayList: " + numbers);
  11. // Creating an instance of Iterator
  12. Iterator<Integer> iterate = numbers.iterator();
  13. // Using the next() method
  14. int number = iterate.next();
  15. System.out.println("Accessed Element: " + number);
  16. // Using the remove() method
  17. iterate.remove();
  18. System.out.println("Removed Element: " + number);
  19. System.out.print("Updated ArrayList: ");
  20. // Using the hasNext() method
  21. while(iterate.hasNext()) {
  22. // Using the forEachRemaining() method
  23. iterate.forEachRemaining((value) -> System.out.print(value + ", "));
  24. }
  25. }
  26. }

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.