The Wayback Machine - https://web.archive.org/web/20240926181340/https://www.geeksforgeeks.org/convert-set-of-string-to-array-of-string-in-java/
Open In App

Convert Set of String to Array of String in Java

Last Updated : 11 Dec, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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]
    


Previous Article
Next Article

Similar Reads

Convert a Set of String to a comma separated String 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" Approach: This can be achieved with the help of join() method of String as fol
1 min read
Convert an ArrayList of String to a String Array in Java
In Java, as we all know ArrayList class is derived from the List interface. Here we are given an ArrayList of strings and the task is to convert the ArrayList to a string array. Illustration: Input : ArrayList = [ "Geeks", "for", "Geeks" ] Output: String[] = {"Geeks", "for", "Geeks"}Input : ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "S
3 min read
How to convert an Array to String in Java?
Below are the various methods to convert an Array to String in Java: Arrays.toString() method: Arrays.toString() method is used to return a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the cha
2 min read
Convert Character Array to String in Java
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character "\0". A character array can be converted to a string and vice versa. In the previous article, we have already discussed how to convert a string to a character array. In this article, we will discu
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Convert Stream to Set in Java
Below given are some methods which can be used to convert Stream to Set in Java. Method 1 : Using Collectors Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set. Stream.collect() method can be used to collect elements of a stream in a container. The
3 min read
Convert a Set to Stream in Java
Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection. Below given are some examples to understand the implementation in a better way. Example 1 : Converting Integer HashSet to Stream of Integers. Java Code // Java code for converting // Set to Stream import java.util.*; imp
2 min read
Program to convert a Set to Stream in Java using Generics
Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are the various methods to convert Set to St
3 min read
Convert List to Set in Java
Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. Few important features of the Java Set interface are as follows: The set interface is an unordered collection of objects in which duplicate values cannot be stored.The
5 min read
Java Program to convert Character Array to IntStream
Given a Character Array, the task is to convert this array into an IntStream containing the ASCII values of the character elements. Examples: Input: char[] = { 'G', 'e', 'e', 'k', 's' } Output: 71, 101, 101, 107, 115 Input: char[] = { 'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's' } Output: 71, 101, 101, 107, 115, 70, 111, 114, 71,
1 min read
Convert byte[] array to File using Java
As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it
3 min read
Program to convert Byte Array to Writer in Java
References: Writer Class Approach: Writer class is used to write character stream, by which byte array can be passed as an argument. By this way, byte array can be converted into Writer class. To get the byte array from String, getBytes() method is used. Below is the implementation of the above approach: Program: // Java Program Convert // Byte Arr
2 min read
How to Convert Vector to Array in Java?
As we all know an array is a group of liked-typed variables that are referred to by a common name while on the other hand vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implement the List interface which gives a superior advantage of using all the methods of List interf
3 min read
How to convert LinkedList to Array in Java?
Given a Linked List in Java, the task is to convert this LinkedList to Array. Examples: Input: LinkedList: ['G', 'e', 'e', 'k', 's'] Output: Array: ['G', 'e', 'e', 'k', 's'] Input: LinkedList: [1, 2, 3, 4, 5] Output: Array: [1, 2, 3, 4, 5] Approach: Get the LinkedListConvert the LinkedList to Object array using toArray() method.Convert the Object a
2 min read
Convert List to Array in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects where duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are given a List be it any LinkedList or ArrayList of stri
5 min read
Convert List of Characters to String in Java
Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are supported internally by a char array. Since arrays
4 min read
Program to convert IntStream to String in Java
Given a Instream containing ASCII values, the task is to convert this Instream into a String containing the characters corresponding to the ASCII values. Examples: Input: IntStream = 71, 101, 101, 107, 115 Output: Geeks Input: IntStream = 71, 101, 101, 107, 115, 70, 111, 114, 71, 101, 101, 107, 115 Output: GeeksForGeeks Algorithm: Get the Instream
1 min read
Program to convert String to IntStream in Java
Given a String, the task is to convert this String into an IntStream containing the ASCII values of the characters as the elements. Examples: Input: String = Geeks Output: 71, 101, 101, 107, 115 Input: String = GeeksForGeeks Output: 71, 101, 101, 107, 115, 70, 111, 114, 71, 101, 101, 107, 115 Algorithm: Get the String to be converted. Convert it in
1 min read
Java Program to Convert String to Date
Given a string in date format, the task is to convert this String into an actual date. Here the main concept is the parse() method which helps in the conversion. Illustration: Input : string = "2018-10-28T15:23:01Z" Output: 2018-10-28T15:23:01Z Input : string = "28 October, 2018" Output: 2018-10-28Different Methods to Convert String to DateUsing in
4 min read
Convert String to Double in Java
Here, we will convert String to Double in Java. There are 3 methods for this Conversion from String to Double as mentioned below: Example of String to Double Conversion Input : String = "20.156"Output: 20.156 Input : String = "456.21"Output : 456.21 Methods for String to Double Conversion Different Ways for Converting String to Double are mentioned
3 min read
Convert String into comma separated List in Java
Given a String, the task is to convert it into comma separated List. Examples: Input: String = "Geeks For Geeks" Output: List = [Geeks, For, Geeks] Input: String = "G e e k s" Output: List = [G, e, e, k, s] Approach: This can be achieved by converting the String into String Array, and then creating an List from that array. However this List can be
2 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
Convert Java Object to Json String using GSON
JSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To convert a Java object into JSON, the following methods can be
2 min read
Convert Json String to Java Object Using GSON
Pre-requisite: Convert Java Object to Json String Using GSONJSON Stand for JavaScript Object Notation. It's a standard text-based format which shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. To co
3 min read
How to convert a String to an Int in Java?
Given a String str containing digits as characters, the task is to convert this given string to an integer in Java. In this article, we will learn how to convert a String to an Int in Java. Examples: Input: str = "1234" Output: 1234 Input: str = "213s" Output: 0 Since the String contains other than digits, hence the integer value will be 0Methods t
3 min read
Java Convert int to String | Different Ways Of Conversion
Converting Integers to Strings involves using the Integer classes toString() or String.valueOf() for direct conversion. String.format() is another method offering flexible formatting options. Using StringBuilder or StringBuffer for appending integer values as strings is efficient for extensive string manipulation. We generally counter with such con
9 min read
Convert a String to a List of Characters in Java
Given a String, the task is to convert it into a List of Characters in Java. Examples: Input: String = "Geeks" Output: [G, e, e, k, s] Input: String = "GeeksForGeeks" Output: [G, e, e, k, s, F, o, r, G, e, e, k, s] Naive Method Get the String. Create an empty List of Characters. Add each character of String to the List. Return the List. Below is th
4 min read
Java.lang.String class in Java | Set 2
Java.lang.String class in Java | Set 1 In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable. Now lets discuss some of the methods provided by String class. Methods: public int codePointAt(int index) - It takes as parameter a index which must be from 0 to length() - 1. a
5 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Convert an Iterable to Collection in Java
Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single
4 min read
Article Tags :
Practice Tags :