Convert Set to Array in Java

Exercise:

Write a Java Program to convert array to set (HashSet).

Click Here to View the Solution!
import java.util.*;
public class SetToArray {
  
     public static void main(String[] args) {
         Set<String> set = new HashSet<>();
         set.add("Hello");
         set.add("World");
         set.add("!");
  
         String[] array = new String[set.size()];
         set.toArray(array);
         System.out.println("Array: " + Arrays.toString(array));
     } 
 }
Click Here to View the Output!
Array: [!, Hello, World]
Click Here to View the Explanation!
  • For converting a HashSet into an array, firstly a HashSet called set is created. To determine the required length of the array to be created, we retrieve the size of the HashSet. Then an array of the same length is created using toArray() method.