Enter your email id to get regular update free
Login
Your Email
Pasword

How to Set to Array in Java?

Try your approach on {IDE} first, before moving on to the solution.

Threee different methos of setting array in Java are:
1. Create an empty array then traverse the given set and one by one add elements to the array.
E.g:
// Conversion of Set to array using simple traversal 
import java.util.*; 
 class Test 
{ public static void main(String[] args) 
{ // hash set of strings 
 Set s = new HashSet(); 
 s.add("Goodluck"); 
 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); 
 }
 }

2.Method 2  is (Using toArray())
import java.util.*;
class Test {
public static void main(String[] args)
 {
Sets.add("Goodluck");
s.add("for");
int n = s.size();
String arr[] = new String[n];
arr = s.toArray(arr);
for (String x : arr)
System.out.println(x);
  }
}

3. 3rd Method is  Using stream in Java to convert given set to steam, then stream to array.
import java.util.*;
class Test {
public static void main(String[] args)
{
Sets.add("Goodluck");
s.add("for");
int n = s.size();
String[] arr = s.stream().toArray(String[] ::new);
for (String x : arr)
System.out.println(x);
}
}
Run these set of code on IDE to check the output .
Set Array
Java
Array in Java
Ayesha
Tech writer at newsandstory
Total 115 views