Iterate through a Collection using Iterator in Java

Description

The following code shows how to iterate through a Collection using Iterator.

Example


/*w ww .j a  v  a2 s.co  m*/
import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {

    ArrayList<String> aList = new ArrayList<String>();

    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");

    Iterator itr = aList.iterator();

    // iterate through the ArrayList values using Iterator's hasNext and next methods

    while (itr.hasNext()){
      System.out.println(itr.next());
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet