How to use Iterator in Java?

Java 8Object Oriented ProgrammingProgramming

Iterator in Java is used to traverse each and every element in the collection. Using it, traverse, obtain each element or you can even remove.

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

The iterator() method is provided by every Collection class. To use an iterator to cycle through the contents of a collection, at first obtain an iterator to the start of the collection by calling the collection's iterator( ) method. After that, set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. At last, within the loop, obtain each element by calling next( ).

Let us now see an example to iterate through the values of ArrayList −

Example

 Live Demo

import java.util.*;
public class Main {
   public static void main(String args[]) {
      ArrayList myList = new ArrayList();
      myList.add("Jack");
      myList.add("Nathan");
      myList.add("Tom");
      myList.add("Ryan");
      myList.add("David");
      myList.add("Kevin");
      myList.add("Steve");
      myList.add("Nathan");
      myList.add("Tim");
      System.out.print("Values\n");
      Iterator i = myList.iterator();
      while(i.hasNext()) {
         Object obj = i.next();
         System.out.print(obj + " ");
      }
      System.out.println();
   }
}

Output

Values
Jack Nathan Tom Ryan David Kevin Steve Nathan Tim
raja
Published on 20-Sep-2019 07:29:51
Advertisements