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:
How to Print LinkedHashSet Elements in Java?
Next article icon

How to Print HashSet Elements in Java?

Last Updated : 09 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In HashSet, duplicates are not allowed. If we are trying to insert duplicates then we won’t get any compile-time or runtime error and the add() method simply returns false.

We can use 2 ways to print HashSet elements:

  1. Using the iterator() method to traverse the set elements and printing it.
  2. Directly printing it using a reference variable.

Method 1: By using Cursor which is Iterator.

  • If we want to get objects one by one from the collection then we should go for the cursor.
  • We can apply the Iterator concept for any Collection Object and hence it is a Universal Cursor.
  • By using Iterator we can perform both read and remove operations.
  • We can create an Iterator object by using the iterator method of Collection Interface.

public Iterator iterator();   //  Iterator method of Collection Interface.

  • Creating an iterator object

Iterator itr = c.iterator();  // where c is any Collection Object like ArrayList,HashSet etc.

Example:

Java




// Java program to print the elements
// of HashSet using iterator cursor
 
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        HashSet<Integer> hs = new HashSet<Integer>();
        hs.add(5);
        hs.add(2);
        hs.add(3);
        hs.add(6);
        hs.add(null);
 
        // print HashSet elements one by one.
        // Insertion order in not preserved and it is based
        // on hash code of objects.
 
        // creates Iterator oblect.
        Iterator itr = hs.iterator();
 
        // check element is present or not. if not loop will
        // break.
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
 
 
Output
null 2 3 5 6

Method 2: We can directly print HashSet elements by using the HashSet object reference variable. It will print the complete HashSet object.

Note: If we do not know the hash code, so you can’t decide the order of insertion.

Example:

Java




// Java program to directly print the
// elements of HashSet
 
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
 
        // create HashSet object
        HashSet<String> hs = new HashSet<String>();
 
        // add element in HashSet object
        hs.add("B");
        hs.add("C");
        hs.add("D");
        hs.add("A");
        hs.add("Z");
        hs.add("null");
        hs.add("10");
 
        // print HashSet
        // we don't know hash code,
        // so we don't know order
        // of insertion
        System.out.println(hs);
    }
}
 
 
Output
[A, B, C, D, null, Z, 10]


Next Article
How to Print LinkedHashSet Elements in Java?

A

amitroy9615
Improve
Article Tags :
  • Java
  • Java Programs
  • Technical Scripter
  • java-hashset
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Convert a HashSet to JSON in Java?
    In Java, a HashSet is an implementation of the Set interface that uses a hash table to store elements. It allows fast lookups and does not allow duplicate elements. Elements in a HashSet are unordered and can be of any object type. In this article, we will see how to convert a HashSet to JSON in Jav
    2 min read
  • How to Print LinkedHashSet Elements in Java?
    LinkedHashSet is a child class of HashSet in which duplicates are not allowed but the insertion order is preserved. The elements are printed in the same order in which they were inserted. There are several ways to print LinkedHashSet elements: By simply printing the elementsBy using enhanced for loo
    5 min read
  • How to Get Elements By Index from HashSet in Java?
    HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. The class does not guarantee the constant order of elements over time but permits the null element. The underlying data structure for HashSet is Hashtable. HashSet also implement
    3 min read
  • How to Convert ArrayList to HashSet in Java?
    ArrayList: In Java, ArrayList can have duplicates as well as maintains insertion order. HashSet: HashSet is the implementation class of Set. It does not allow duplicates and uses Hashtable internally. There are four ways to convert ArrayList to HashSet : Using constructor.Using add() method by itera
    3 min read
  • How to Convert Comma Separated String to HashSet in Java?
    Given a Set of String, the task is to convert the Set to a comma-separated String in Java. Examples: Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: Set<String> = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" There are two ways in which
    2 min read
  • How to Convert List of Lists to HashSet in Java?
    In Java, Collections like lists, and sets play a crucial role in converting and manipulating the data efficiently. The Conversion of a List of Lists into a HashSet is mainly used to Remove Duplicates and ensures the programmer maintains the unique data of elements. Example to Convert List of Lists t
    2 min read
  • How to Serialize and Deserialize a HashSet in Java?
    Serialization is the technique of converting an object's state into a byte stream. The main purpose of serialization is to save the state of an object so that it can be rebuilt later. In Java, a Serializable interface is used to mark classes as serializable. When a class implements the Serializable
    3 min read
  • How to Get Random Elements from LinkedHashSet in Java?
    LinkedHashSet is used to maintain the insertion order and for generating random elements from LinkedHashSet we will use Random Class to generate a random number between 0 and the LinkedHashSet size. That random number will act as the index of LinkedHashSet. We can get a random element in three ways:
    3 min read
  • How to Iterate HashSet in Java?
    HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. Methods to It
    3 min read
  • How to Copy or Append HashSet to Another HashSet in Java?
    HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements' order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. We can copy or append a HashSet to another Hash
    4 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