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.

Example

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>();
      set.add("Apple");
      set.add("Orange");
      set.add("Banana");

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

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

Output

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

Updated on: 13-Mar-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements