Convert Set to Array in Java


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<>();
         String[] array = new String[set.size()];
         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.