Set to Array in Java

Given a set (HashSet or TreeSet) of strings in Java, convert it into an array of strings.

Input : Set hash_Set = new HashSet();
        hash_Set.add("Geeks");
        hash_Set.add("For");
Output : String arr[] = {"Geeks", "for"}


Method 1 (Simple)
We simply create an empty array. We traverse the given set and one by one add elements to the array.

// Java program to demonstrate conversion of 
// Set to array using simple traversal
import java.util.*;

class Test {
    public static void main(String[] args)
    {
        // Creating a hash set of strings
        Set<String> s = new HashSet<String>();
        s.add("Geeks");
        s.add("for");

        int n = s.size();
        String arr[] = new String[n];

        int i = 0;
        for (String x : s)
            arr[i++] = x;

        for (String x : arr)
            System.out.println(x);
    }
}
Output:

Geeks
for

Method 2 (Using toArray())

// Java program to demonstrate conversion of 
// Set to array using toArray()
import java.util.*;

class Test {
    public static void main(String[] args)
    {
        // Creating a hash set of strings
        Set<String> s = new HashSet<String>();
        s.add("Geeks");
        s.add("for");

        int n = s.size();
        String arr[] = new String[n];

        // Please refer below post for syntax
        // details of toArray()
        // https://www.geeksforgeeks.org/arraylist-array-conversion-java-toarray-methods/
        arr = s.toArray(arr);

        for (String x : arr)
            System.out.println(x);
    }
}
Output:

Geeks
for

Method 3 (Using stream in Java)
We use stream in Java to convert given set to steam, then stream to array. This works only in Java 8 or versions after that.

// Java program to demonstrate conversion of 
// Set to array using stream
import java.util.*;

class Test {
    public static void main(String[] args)
    {
        // Creating a hash set of strings
        Set<String> s = new HashSet<String>();
        s.add("Geeks");
        s.add("for");

        int n = s.size();
        String[] arr = s.stream().toArray(String[] ::new);

        for (String x : arr)
            System.out.println(x);
    }
}
Output:

Geeks
for



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:



1.5 Average Difficulty : 1.5/5.0
Based on 4 vote(s)