Java - How to iterate over Set/HashSet

Posted on October 23, 2016


In this section, we will see the examples of iterating over the HashSet. We will iterate Set by using

  • For-Each loop
  • Iterator interface
  • Stream (Introduced in Java8)

IterateSetExample.java

package com.boraji.tutorial;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author imssbora
 *
 */
public class IterateSetExample {
   public static void main(String[] args) {
      Set<String> set = new HashSet<>(Arrays
            .asList(new String[] { "Java", "Jsp", "Servlet", "Jdbc", "Collection" }));

      /* Method 1 - Iterating using for loop */
      System.out.println("Method 1 - Iterating using for-each loop");
      for (String string : set) {
         System.out.println(string);
      }

      /* Method 2 - Iterating using Iterator */
      System.out.println("\nMethod 2 - Iterating using Iterator");
      Iterator<String> iterator = set.iterator();
      while (iterator.hasNext()) {
         System.out.println(iterator.next());
      }

      /* Method 3 - Iterating using Stream */
      System.out.println("\nMethod 3 - Iterating using Stream");
      set.stream().forEach(a -> System.out.println(a));

   }
}

Output

Method 1 - Iterating using for-each loop
Java
Jsp
Jdbc
Servlet
Collection

Method 2 - Iterating using Iterator
Java
Jsp
Jdbc
Servlet
Collection

Method 3 - Iterating using Stream
Java
Jsp
Jdbc
Servlet
Collection