Java program to convert a Set to an array

The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. To convert a Set object to an array −

  •  Create a Set object.
  •  Add elements to it.
  •  Create an empty array with size of the created Set.
  •  Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it.
  •  Print the contents of the array.


Live Demo

import java.util.HashSet;
import java.util.Set;
public class SetToArray {
   public static void main(String args[]){
      Set<String> set = new HashSet<String>();

      System.out.println("Contents of Set ::"+set);
      String[] myArray = new String[set.size()];

      for(int i=0; i<myArray.length; i++){
         System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]);


Contents of Set ::[Apple, Orange, Banana]
Element at the index 1 is ::Apple
Element at the index 2 is ::Orange
Element at the index 3 is ::Banana
Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician