Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here


Java - different ways of how to iterate over Set or HashSet

0 contributions
14 points

1. Overview

In java we can traverse over Set or HashSet with different ways.

Old ways involve Iterator, with java 8 we can use stream / forEach.

There is also an ancient way with Enumeration.

Below we can see 7 different ways of how to iterate over Set in java.

2. Code example

import java.util.*;

public class JavaIterateOverHashSet {

    public static void main(String[] args) {

        Set<String> set = new HashSet<>();

        for (String s : set) {
            System.out.print(s + ", ");

        System.out.println("\n#2"); // java 8
        set.forEach(s -> {
            System.out.print(s + ", ");

        System.out.println("\n#3"); // java 8
        set.forEach(s -> System.out.print(s + ", "));

        System.out.println("\n#4");  // java 8

        System.out.println("\n#5");  // java 8;

        Iterator<String> itr = set.iterator();
        while (itr.hasNext()) {
            System.out.print( + ", ");

        Enumeration elements = new Vector(set).elements();
        while (elements.hasMoreElements()) {
            System.out.print(elements.nextElement() + ", ");


A, B, C, 
A, B, C, 
A, B, C, 
A, B, C, 
A, B, C, 


0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more