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; System.out.println(Arrays.toString(arr)); } } |
[Geeks, for]
Method 2 (Using System.arraycopy())
// 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]; // Copying contents of s to arr[] System.arraycopy(s.toArray(), 0 , arr, 0 , n); System.out.println(Arrays.toString(arr)); } } |
[Geeks, for]
Method 3 (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() arr = s.toArray(arr); System.out.println(Arrays.toString(arr)); } } |
[Geeks, for]
Method 4 (Using Arrays.copyOf())
// Java program to demonstrate conversion of // Set to array using Arrays.copyOf() 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" ); String[] arr = Arrays.copyOf(s.toArray(), s.size(), String[]. class ); System.out.println(Arrays.toString(arr)); } } |
[Geeks, for]
Method 5 (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 ); System.out.println(Arrays.toString(arr)); } } |
[Geeks, for]