Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Convert HashSet to array in Java
Next article icon

Convert HashSet to array in Java

Last Updated : 11 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Java HashSet class is used to create a collection that uses a hash table for the storage of elements. It inherits AbstractSet class and implements Set Interface. 

The key points about HashSet are:

  • HashSet contains unique elements only.
  • HashSet allows null values.
  • The insertion of elements in a HashSet is based on a hashcode.
  • HashSet is best used for searching problems.

There are two ways of converting HashSet to the array:

  1. Traverse through the HashSet and add every element to the array.
  2. To convert a HashSet into an array in java, we can use the function of toArray().

Method 1: By traversing the set add elements to the array

We can traverse the Set using a simple for loop and then add elements one by one to the array.

Java
// Java program to convert HashSet to array  import java.io.*; import java.util.*;  class GFG {     public static void main(String[] args)     {         HashSet<String> set = new HashSet<String>();         set.add("1");         set.add("13");         set.add("27");         set.add("87");         set.add("19");          System.out.println("Hash Set Contains :" + set);         String arr[] = new String[set.size()];                  int i=0;                // iterating over the hashset         for(String ele:set){           arr[i++] = ele;         }          for (String n : arr)             System.out.println(n);     } } 

Output
Hash Set Contains :[1, 13, 27, 19, 87]  1  13  27  19  87

Method 2: Using toArray() method

Syntax:

public Object[] toArray()             or  public <T> T[] toArray(T[] a)

Parameters: This method either accepts no parameters or it takes an array T[] a as a parameter which is the array into which the elements of the list are to be stored if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value: The function returns an array containing all the elements in this list.

Java
// Java program to convert HashSet to array  import java.io.*; import java.util.*;  class GFG {     public static void main(String[] args)     {         HashSet<String> set = new HashSet<String>();         set.add("1");         set.add("13");         set.add("27");         set.add("87");         set.add("19");          System.out.println("Hash Set Contains :" + set);         String arr[] = new String[set.size()];                // toArray() method converts the set to array         set.toArray(arr);          for (String n : arr)             System.out.println(n);     } } 

Output
Hash Set Contains :[1, 13, 27, 19, 87]  1  13  27  19  87

Next Article
Convert HashSet to array in Java

I

itatha42
Improve
Article Tags :
  • Java
  • Java Programs
Practice Tags :
  • Java

Similar Reads

    Convert HashSet to a ArrayList in Java
    ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can b
    4 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
    Convert a HashSet to a LinkedList in Java
    In Java, HashSet and LinkedList are linear data structures. These are majorly used in many cases. There may be some cases where we need to convert HashSet to LinkedList. So, in this article, we will see how to convert HashSet to LinkedList in Java. Java Program to Convert a HashSet to a LinkedList T
    2 min read
    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
    Program to convert Array to Set in Java
    Array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In cas
    7 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