Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java HashSet isEmpty() Method
Next article icon

Java HashSet iterator() Method

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The HashSet iterator() method in Java is used to return an iterator that can be used to iterate over the elements in a HashSet. HashSet does not maintain any specific order of its elements, so the elements are returned in random order when iterated over. The iterator() method provides a way to traverse the elements in the set, allowing you to access them one by one.

Example 1: Iterating over a HashSet of Integers

Java
// Java Program to demonstrates the working of  // iterator() over a HashSet of Integers import java.util.HashSet; import java.util.Iterator;  public class Geeks {     public static void main(String[] args)     {         // Create a HashSet         HashSet<Integer> hs = new HashSet<>();          // Add elements to the HashSet         hs.add(10);         hs.add(20);         hs.add(30);          // Get the iterator         Iterator<Integer> i = hs.iterator();          // Traverse the HashSet using the iterator         System.out.println("HashSet: " + hs);         System.out.print("The iterator values are: ");         while (i.hasNext()) {             System.out.print(i.next() + " ");         }     } } 

Output
HashSet: [20, 10, 30] The iterator values are: 20 10 30 

Note: The order of elements in a HashSet is not guaranteed and can vary each time the program runs, as shown in the output.

Syntax of HashSet iterator() Method

public Iterator<E> iterator();

Return Type: This method returns an Iterator object to traverse the elements in the collection one by one.

Example 2: Iterating over a HashSet of Custom Objects

In this example, we will demonstrate how to store custom object “Employee” in a HashSet and iterate through them using an iterator.

Java
// Java program to demonstrates the use of HashSet to store // of HashSet to store custom objects and the traversal  // of these objects using an iterator import java.util.HashSet; import java.util.Iterator;  public class Geeks {     public static void main(String args[])     {          // create hash set         HashSet<Employee> hs = new HashSet<>();          hs.add(new Employee(10, "Geek1"));         hs.add(new Employee(2, "Geek20"));         hs.add(new Employee(35, "Geek5"));          // create an iterator         Iterator<Employee> i = hs.iterator();          // iterate through the HashSet and          // print each employee object         while (i.hasNext()) {             System.out.println("Value: " + i.next() + " ");         }     } }  // create a class representing Employee class Employee {     int id;     String name;      Employee(int id, String name)     {         this.id = id;         this.name = name;     }     // Override the toString() to provide the string     // representation of the Employee object     @Override public String toString()     {         return "[ " + this.id + ", " + this.name             + " ]";     } } 

Output
Value: [ 35, Geek5 ]  Value: [ 10, Geek1 ]  Value: [ 2, Geek20 ]  


Next Article
Java HashSet isEmpty() Method
author
chinmoy lenka
Improve
Article Tags :
  • Java
  • Java-Collections
  • java-hashset
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • Java HashSet
    HashSet in Java implements the Set interface of Collections Framework. It is used to store the unique elements and it doesn't maintain any specific order of elements. Can store the Null values.Uses HashMap (implementation of hash table data structure) internally.Also implements Serializable and Clon
    12 min read
  • Java HashSet add() Method
    The HashSet add() method in Java is used to add a specific element to the set. This method will add the element only if the specified element is not present in the HashSet. If the element already exists, the method will not add it again. This method ensures that no duplicate elements are added to th
    2 min read
  • Java HashSet clear() Method
    The clear() method of the HashSet class in Java is used to clear all the elements from the HahSet. This method makes the HashSet empty but does not delete the HashSet itself. It simply removes all elements, leaving the set ready for reuse. Syntax of HashSet clear() Methodvoid clear() Key Points: Aft
    1 min read
  • Java HashSet contains() Method
    The contains() method of the HashSet class in Java is used to check if a specific element is present in the HashSet or not. So, mainly it is used to check if a set contains any particular element. [GFGTABS] Java // Java program to demonstrates the working of contains() import java.util.*; public cla
    1 min read
  • HashSet remove() Method in Java
    The HashSet remove() method in Java is used to remove a specific element from the set if it is present. Note: HashSet and the remove() were introduced in JDK 1.2 as part of the Collections Framework and are not available in earlier versions of Java (JDK 1.0 and JDK 1.1). Example 1: Here, the remove(
    2 min read
  • Java HashSet iterator() Method
    The HashSet iterator() method in Java is used to return an iterator that can be used to iterate over the elements in a HashSet. HashSet does not maintain any specific order of its elements, so the elements are returned in random order when iterated over. The iterator() method provides a way to trave
    3 min read
  • Java HashSet isEmpty() Method
    The HashSet isEmpty() in Java is used to check if the HashSet is empty or not. Syntax of HashSet isEmpty() Methodboolean isEmpty() Return Type: This method returns "true" if the HashSet is empty, otherwise returns "false". Example: This example demonstrates how the isEmpty() method checks whether th
    1 min read
  • Java HashSet size() Method
    The HashSet size() method in Java is used to get the size of the HashSet or the number of elements present in the HashSet. Syntax of HashSet size() Methodint size() Return Type: This method returns an integer value that represents the number of elements currently stored in the HashSet. Example: This
    1 min read
  • Java HashSet clone() Method
    The HashSet clone() method in Java is used to return a shallow copy of the given HashSet. It just creates a copy of the set. Syntax of HashSet clone() Methodpublic Object clone() Return Type: This method returns a new HashSet object that contains the same element as the original set. Example: This e
    1 min read
  • Java AbstractSet equals() Method
    The AbstractSet equals() Method in Java is used to check for equality between two sets. This method verifies whether the elements of one set are equal to the elements of another set. Syntax of AbstractSet equals() Methodpublic boolean equals(Object o) Parameter: The object "o" is to be compared for
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences