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:
Program to convert Array to Set in Java
Next article icon

Convert Set of String to Array of String in Java

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

Given a Set of Strings, the task is to convert the Set into an Array of Strings in Java.

Examples:

  Input: Set<String>: ["ForGeeks", "A Computer Portal", "Geeks"]  Output: String[]: ["ForGeeks", "A Computer Portal", "Geeks"]    Input: Set<String>: ["G", "e", "k", "s"]  Output: String[]: ["G", "e", "k", "s"]  
  • Method 1: Naive Method.
    1. Get the Set of Strings.
    2. Create an empty Array of String of size as that of the Set of String.
    3. Using advanced for loop, copy each element of the Set of String into the Array of String.
    4. Return or print the Array of String.

    Below is the implementation of the above approach:




    // Java program to convert
    // Set of Strings to Array of Strings
      
    import java.util.Arrays;
    import java.util.Set;
    import java.util.HashSet;
      
    class GFG {
      
        // Function to convert Set<String> to String[]
        public static String[] convert(Set<String> setOfString)
        {
      
            // Create String[] of size of setOfString
            String[] arrayOfString = new String[setOfString.size()];
      
            // Copy elements from set to string array
            // using advanced for loop
            int index = 0;
            for (String str : setOfString)
                arrayOfString[index++] = str;
      
            // return the formed String[]
            return arrayOfString;
        }
      
        public static void main(String[] args)
        {
      
            // Get the Set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("Geeks",
                                  "ForGeeks",
                                  "A Computer Portal"));
      
            // Print the setOfString
            System.out.println("Set of String: "
                               + setOfString);
      
            // Convert Set to String array
            String[] arrayOfString = convert(setOfString);
      
            // Print the arrayOfString
            System.out.println("Array of String: "
                               + Arrays.toString(arrayOfString));
        }
    }
     
     
    Output:
      Set of String: [ForGeeks, A Computer Portal, Geeks]  Array of String: [ForGeeks, A Computer Portal, Geeks]  
  • Method 2: Using Set.toArray() method.
    1. Get the Set of Strings.
    2. Convert the Set of String to Array of String using Set.toArray() method by passing an
      empty array of String type. JVM will allocate memory for string array.
    3. Return or print the Array of String.

    Below is the implementation of the above approach:




    // Java program to convert
    // Set of Strings to Array of Strings
      
    import java.util.Arrays;
    import java.util.Set;
    import java.util.HashSet;
      
    class GFG {
      
        // Function to convert Set<String> to String[]
        public static String[] convert(Set<String> setOfString)
        {
      
            // Create String[]  from setOfString
            String[] arrayOfString = setOfString
                                         .toArray(new String[0]);
      
            // return the formed String[]
            return arrayOfString;
        }
      
        public static void main(String[] args)
        {
      
            // Get the Set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("Geeks",
                                  "ForGeeks",
                                  "A Computer Portal"));
      
            // Print the setOfString
            System.out.println("Set of String: "
                               + setOfString);
      
            // Convert Set to String array
            String[] arrayOfString = convert(setOfString);
      
            // Print the arrayOfString
            System.out.println("Array of String: "
                               + Arrays.toString(arrayOfString));
        }
    }
     
     
    Output:
      Set of String: [ForGeeks, A Computer Portal, Geeks]  Array of String: [ForGeeks, A Computer Portal, Geeks]  
  • Method 3: Using Arrays.copyOf() method.
    1. Get the Set of Strings.
    2. Convert the Set of String to Array of String using Arrays.copyOf() method by passing the Set of String, the size of the Set of String, and the desired output type as the String[].
    3. Return or print the Array of String.

    Below is the implementation of the above approach:




    // Java program to convert
    // Set of Strings to Array of Strings
      
    import java.util.Arrays;
    import java.util.Set;
    import java.util.HashSet;
      
    class GFG {
      
        // Function to convert Set<String> to String[]
        public static String[] convert(Set<String> setOfString)
        {
      
            // Create String[]  from setOfString
            String[] arrayOfString = Arrays
                                         .copyOf(
                                             setOfString.toArray(),
                                             setOfString.size(),
                                             String[].class);
      
            // return the formed String[]
            return arrayOfString;
        }
      
        public static void main(String[] args)
        {
      
            // Get the Set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("Geeks",
                                  "ForGeeks",
                                  "A Computer Portal"));
      
            // Print the setOfString
            System.out.println("Set of String: "
                               + setOfString);
      
            // Convert Set to String array
            String[] arrayOfString = convert(setOfString);
      
            // Print the arrayOfString
            System.out.println("Array of String: "
                               + Arrays.toString(arrayOfString));
        }
    }
     
     
    Output:
      Set of String: [ForGeeks, A Computer Portal, Geeks]  Array of String: [ForGeeks, A Computer Portal, Geeks]  
  • Method 4: Using System.arraycopy() method.
    1. Get the Set of Strings.
    2. Convert the Set of String to Array of String using System.arraycopy() method.
    3. Return or print the Array of String.

    Below is the implementation of the above approach:




    // Java program to convert
    // Set of Strings to Array of Strings
      
    import java.util.Arrays;
    import java.util.Set;
    import java.util.HashSet;
      
    class GFG {
      
        // Function to convert Set<String> to String[]
        public static String[] convert(Set<String> setOfString)
        {
      
            // Create String[] of size of setOfString
            String[] arrayOfString = new String[setOfString.size()];
      
            // Convert setOfString to String[]
            System.arraycopy(
                // source
                setOfString.toArray(),
      
                // from index to be copied from Source
                0,
      
                // Destination
                arrayOfString,
      
                // From index where to be copied in Destination
                0,
      
                // Number of elements to be copied
                setOfString.size());
      
            // return the formed String[]
            return arrayOfString;
        }
      
        public static void main(String[] args)
        {
      
            // Get the Set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("Geeks",
                                  "ForGeeks",
                                  "A Computer Portal"));
      
            // Print the setOfString
            System.out.println("Set of String: "
                               + setOfString);
      
            // Convert Set to String array
            String[] arrayOfString = convert(setOfString);
      
            // Print the arrayOfString
            System.out.println("Array of String: "
                               + Arrays.toString(arrayOfString));
        }
    }
     
     
    Output:
      Set of String: [ForGeeks, A Computer Portal, Geeks]  Array of String: [ForGeeks, A Computer Portal, Geeks]  
  • Method 5: Using Java 8 Streams.
    1. Get the Set of Strings.
    2. Convert the Set of String to Stream using stream() method.
    3. Convert the Stream to String[] using toArray() method.
    4. Return or print the Array of String.

    Below is the implementation of the above approach:




    // Java program to convert
    // Set of Strings to Array of Strings
      
    import java.util.Arrays;
    import java.util.Set;
    import java.util.HashSet;
      
    class GFG {
      
        // Function to convert Set<String> to String[]
        public static String[] convert(Set<String> setOfString)
        {
      
            // Create String[] from setOfString
            String[] arrayOfString = setOfString
      
                                         // Convert Set of String
                                         // to Stream<String>
                                         .stream()
      
                                         // Convert Stream<String>
                                         // to String[]
                                         .toArray(String[] ::new);
      
            // return the formed String[]
            return arrayOfString;
        }
      
        public static void main(String[] args)
        {
      
            // Get the Set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("Geeks",
                                  "ForGeeks",
                                  "A Computer Portal"));
      
            // Print the setOfString
            System.out.println("Set of String: "
                               + setOfString);
      
            // Convert Set to String array
            String[] arrayOfString = convert(setOfString);
      
            // Print the arrayOfString
            System.out.println("Array of String: "
                               + Arrays.toString(arrayOfString));
        }
    }
     
     
    Output:
      Set of String: [ForGeeks, A Computer Portal, Geeks]  Array of String: [ForGeeks, A Computer Portal, Geeks]  


Next Article
Program to convert Array to Set in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Set in Java
    The Set Interface is present in java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It is an interface that implements the mathematical set. This interface adds a feature that restricts the insertion of duplicat
    14 min read
  • AbstractSet Class in Java
    In Java, the AbstractSet class is part of the Java Collections Framework. It provides a Skeleton implementation of the set interface, which is a collection that does not allow duplicate elements. This class is abstract, meaning it cannot be instantiated directly, but it can be extended to create a c
    9 min read
  • EnumSet in Java
    In Java, the EnumSet is a specialized set implementation for use with enum types. It is a part of java.util package and provides a highly optimized set for storing enum constants. The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. It extends
    9 min read
  • 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
  • TreeSet in Java
    TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree(red - black tree) for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equ
    13 min read
  • ConcurrentSkipListSet in Java
    In Java, the ConcurrentSkipListSet is the part of the java.util.concurrent package and provides a scalable, thread-safe alternative to TreeSet. It is a sorted set that lets multiple threads safely access and modify the set at the same time without causing issues. It is thread-safe.Elements are in so
    7 min read
  • CopyOnWriteArraySet in Java
    In Java, the CopyOnWriteArraySet is the part of the java.util.concurrent package and is used to handle thread-safe operations in multi-threaded environments. It is ideal when the set is frequently read but infrequently modified. The set ensures safe access for multiple threads, as it creates a new c
    6 min read
  • Java LinkedHashSet
    LinkedHashSet in Java implements the Set interface of the Collection Framework. It combines the functionality of a HashSet with a LinkedList to maintain the insertion order of elements. Stores unique elements only.Maintains insertion order.Provides faster iteration compared to HashSet.Allows null el
    8 min read
  • Convert HashSet to TreeSet in Java
    Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is
    3 min read
  • Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
    In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHa
    6 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