eguruchela

What is iterator?


An iterator is an object that contains a countable number of values. It is an object that can be iterated upon means that we can traverse through all the values.

In Python/Java an iterator is an object which implements the iterator protocol which consist of the methods __iter__() and __next__() .

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.

It is called an "iterator" because "iterating" is the technical term for looping.

To use an Iterator, we will import from the java.util package.

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
  
    // Make a collection
    ArrayList<String> colr = new ArrayList<String>();
    colr.add("Red");
    colr.add("Blue");
    colr.add("Yellow");
 
    // Get the iterator
    Iterator<String> it = cars.iterator();
  
    // Print the first item
    System.out.println(it.next());
  }
}

👈       👉