How to iterate HashSet in Java?


The Java HashSet class employs a hash table internally to implement the Set interface, which uses a HashMap instance. The class does not guarantee that the items will remain the same over time because the iteration order of the factors within the hash set is not always guaranteed.

Null elements may be included in this class. The hash function provides efficient performance for fundamental operations like add, delete, contains, and size, assuming it effectively distributes the elements through the buckets.

The Set interface is implemented by HashSet, which extends AbstractSet. It creates a collection using the hashing technique and saves its data in a hash table. Hashing is the process of generating a unique value, known as a key's hash code, from the data in a key.

Methods Used

A HashSet can be iterated over in one of the three methods that follow −

  • Employing Iterator

  • Instead of using an iterator, utilise a for loop.

  • Making use of the for-each loop

Method 1: Employing Iterator

In this method, we use an iterator to iterate over a HashSet. Initially, we create an iterator the use of the iterator() method in Java, this is specially designed for HashSet.

Syntax

Iterator<Integer> it = set.iterator();

Next, we use Java's hasNext() and next() methods to traverse across the HashSet. The next() method permits us to retrieve the data stored inside the HashSet, while the hasNext() method determines whether the HashSet consists of any extra components.

Please be conscious that this method can be used to iterate through and manipulate the factors of a HashSet.

set.add()

The below code utilizes a HashSet to store a collection of strings. It then uses an iterator to traverse through the HashSet and print each string value.

Algorithm

  • Step 1 − Create a HashSet object called set.

  • Step 2 − Add the strings "Java", "PHP", "Ruby", and "Python" to the set object.

  • Step 3 − Create an Iterator object called itr for the set object.

  • Step 4 − While iterating through the itr object, print each element using a while loop.

Example

import java.util.*;  
public class HashSetIteratorInstance {  
   public static void main(String[] args) {  
      HashSet<String> set=new HashSet<String>();    
      set.add("Java");    
      set.add("PHP");    
      set.add("Ruby");    
      set.add("Python");   
      
      //Traversing elements    
      Iterator<String> itr=set.iterator();    
      while(itr.hasNext()){    
         System.out.println(itr.next());    
      }    
   }  
}

Output

Java
PHP
Ruby
Python

Method 2: Using a for loop

To loop over Set using an improved for loop, there are no special steps to take; you simply use Set as directed by the loop construct.

for()

The code creates a HashSet object and provides strings to it. Then, it makes use of a for loop to iterate via the HashSet object and print each element.

Algorithm

  • Step 1 − Create “TLP” class.

  • Step 2 − Create a HashSet object called set.

  • Step 3 − Add the strings "Welcome", "Tutorialspoint", "CSE", "Students", "for", and "Students" to the set object.

  • Step 4 − Print the message "Iterate HashSet using for loop: ".

  • Step 5 − Use a for loop to traverse through the set object and print each element.

Example

// Java program to iterate the HashSet with the help of for loop
  
import java.util.*;
  
public class TLP {
   public static void main(String[] args){
      HashSet<String> set = new HashSet<>();

      // Addition of data to HashSet
      set.add("Welcome");
      set.add("Tutorialspoint");
      set.add("CSE");
      set.add("Students");
      set.add("for");
      set.add("Students");

      System.out.println("Iterate HashSet with the help of for loop : ");
      for (String ele : set) {
         System.out.print(ele + " ");
      }
   }
}

Output

Iterate HashSet using for loop : 
CSE Students for Welcome Tutorialspoint

Method 3: Using a for each loop

Only Java 8 and later versions support this function. Since Set implements the Iterable interface, you can employ its forEach() function to iterate through Set.

forEach()

The code creates a HashSet, adds more than one programming language names to it, after which prints each element inside the HashSet the usage of a for-each loop.

Algorithm

  • Step 1 − Import the java.util package.

  • Step 2 − Come up with a HashSet object - “hashset.”

  • Step 3 − Now you must add the following strings to the hashset object: "Java", "Python", "C sharp", "PHP", and "Ruby".

  • Step 4 − Print the following message: "HashSet consists of :".

  • Step 5 − Use a for loop to traverse through the hashset object and print each string.

Example

import java.util.*;

public class HashSetIteratorInstance {
   public static void main(String args[]) {

      // Declare a HashSet
      HashSet<String> hashset = new HashSet<String>();
      
      // Add elements to HashSet
      hashset.add("Java");
      hashset.add("Python");
      hashset.add("C sharp");
      hashset.add("PHP");
      hashset.add("Ruby");

      System.out.println("HashSet consists of :");
      
      // Using for each loop
      for(String str : hashset){
         System.out.println(str);
      }
   }
}

Output

HashSet consists of :
Java
PHP
C sharp
Ruby
Python

Conclusion

We have discussed three methods to iterate a HashSet in Java: the usage of an iterator, a for loop, or a for-each loop. The iteration order isn't assured, but all three methods work.

To iterate a HashSet in Java, you may use an iterator, which is a completely unique object that helps you to get access to the elements of the set one by one.

You could also iterate a HashSet using a for loop. However, it could be much less efficient than the usage of an iterator.

Finally, you could iterate a HashSet using a for-each loop.

Updated on: 18-Oct-2023

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements