Java Iterator

Java Iterator


Iterator In Java 
  • Often, you will want to cycle through the elements in a collection.
  • For example, you might want to display each element.
  • One way to do this is to employ an iterator.
  • Before you can access a collection through an iterator,you must have one 
  • Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection.
  •  By using this iterator object, you can access each element in the collection, one element at a time.
  • In general, to use an iterator to cycle through the contents of a collection, follow these steps -
  1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.
  2.  Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  3.  Within the loop, obtain each element by calling next( ).
Following are the methods used to iterate in Collections in Java - 
Example -
package javaLearnings;

import java.util.*;

// Web desining House

// Online Promotion House
// Demonstrate Iterator -.
public class Main {

  public static void main(String args[]) {
// Create an array list.
      ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
      al.add("W");
      al.add("E");
      al.add("B");
      al.add("S");
      al.add("I");
      al.add("T");
      al.add("E");
      // Use iterator to display contents of al.
      System.out.print("Original contents of al: ");
      Iterator<String> itr = al.iterator();
      while(itr.hasNext()) {
          String element = itr.next();
          System.out.print(element + " ");
      }
      System.out.println();
// Modify objects being iterated.
      ListIterator<String> litr = al.listIterator();
      while(litr.hasNext()) {
          String element = litr.next();
          litr.set(element + "+");
      }
      System.out.print("Modified contents of al: ");
      itr = al.iterator();
      while(itr.hasNext()) {
          String element = itr.next();
          System.out.print(element + " ");
      }
      System.out.println();
// Now, display the list backwards.
      System.out.print("Modified list backwards: ");
      while(litr.hasPrevious()) {
          String element = litr.previous();
          System.out.print(element + " ");
      }
      System.out.println();
  }
      }
Output - 
We can also use FOR-each loop instead of iterator() method is as follow:
Example-
Output -