Java program to convert a Set to an array

Object Oriented ProgrammingJava8Java Programming

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
raja
Published on 26-Apr-2018 12:09:49
Advertisements