What are Iterators in Java?
Java provides an interface called Iterator that is used to iterate over or loop through the elements in a collection. You can use an iterator on any Collection interfaces or any of its sub interfaces like List or Set . Consider the following code snippet: public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i &lt; 10; i ++){ list.add(i+2); } Iterator<Integer> itr = list.iterator(); while (itr.hasNext()){ int i = itr.next(); System.out.println("i="+i); } } This code demonstrates how you can use iterator to iterate over a List. Here, we are iterating over a list of integers. But you can use it to iterate over any data type. The iterator method on the list interface returns an iterator instance. In the iterator variable declaration, we need to specify the data type that the iterator will iterate over. In this case, we are specifying Integer. Once we obtain an iterator, we can use it