Tutorials

Collection Programs


HashSet Traversal


In this chapter, our task is:

  • We will create a HashSet
  • We will add elements to HashSet (duplicate as well)
  • Traverse the HashSet using Iterator 
  • We will print the set

Example: Traverse elements of HashSet using Iterator in java


package javaRadarHashSet;

import java.util.HashSet;
import java.util.Iterator;

public class ItrTraversal {

       public static void main(String[] args) {

          //create HashSet
            HashSet javaRadarSet = new HashSet();

          //Add elements to HashSet
            javaRadarSet.add("Java");
            javaRadarSet.add("Java");
            javaRadarSet.add("Spring");
            javaRadarSet.add("Hibernate");
            javaRadarSet.add("EJB");



          //creating iterator to traverse over javaRadarSet
            Iterator setIterator = javaRadarSet.iterator();

            while(setIterator.hasNext()){

               System.out.println(setIterator.next());

            }

      }

}

OUTPUT

Java
Hibernate
Spring
EJB
 
Duplicate element java is removed. As set doesn't allow addition of duplicate elements.
 

 



Please Share this page
Views : 28