Different ways to Iterate Set

Published May 18, 2022

In Java, a set is used to build collections that use hash tables to store data. Sets store information through a mechanism known as hashing. As a result of hashing, the informational content of a key determines its unique value, called its hash code.

There are two common ways you can use to iterate over a hash set in Java:

  • Using an Iterator method

  • Without using the Iterator method

 

Using Iterator method

In this example, we are going to create a Set using the HashSet class and use the iterator() method to iterate over the set.

Example

import java.util.HashSet;

import java.util.Iterator;

public class Iterate_set_using_iterators {

 

            public static void main(String[] args) {

                HashSet<String> hashmanset = new HashSet<String>();

                hashmanset.add("Python");

                hashmanset.add("Kotlin");

                hashmanset.add("Java");

                Iterator<String> a = hashmanset.iterator();

                while(a.hasNext()){

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

                }

            }

}

Output

Java

Python

Kotlin

 

Without Using the Iterator method

In this example, we have not used an iterator, however, we have used  the for-each method  to iterate  each element of a set

import java.util.HashSet;

import java.util.Set;

public class Iterate_set_Without_Using_Iterator_method {

            public static void main(String[] args) {

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

                hset.add("Python");

                hset.add("java");

                hset.add("Kotlin");

             

                for (String temp : hset) {

                    System.out.println(temp);

                }

            }

}

 

Output

java

Python

Kotlin

 

Keyword: How to Iterate over a Set , List Iterator, Set Iterator

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

116 Views