Iterate through elements of HashSet in Java

Description

The following code shows how to iterate through elements of HashSet.

Example


//from   w w  w.ja v a  2 s  .  co  m
import java.util.HashSet;
import java.util.Iterator;

public class Main {

  public static void main(String[] args) {

    HashSet<Integer> hSet = new HashSet<Integer>();

    hSet.add(new Integer("1"));
    hSet.add(new Integer("2"));
    hSet.add(new Integer("3"));

    Iterator itr = hSet.iterator();

    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