Convert HashSet to Array in Java with Example

In the last tutorial we have learnt how to iterate over a HashSet/Set. In this post we will convert HashSet to an Array.

We will use toArray() method to convert HashSet to an Array.


Program to Convert HashSet to Array in Java




import java.util.*;

 public class HashSettoArray {
    public static void main(String args[]) {
        
    // Declaring a HashSet
    HashSet<String> hashset = new HashSet<String>();
    // Add elements to HashSet
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    hashset.add("Papaya");
    hashset.add("Banana");
    //Showing HashSet elements
    System.out.println("HashSet contains :" + hashset);
    // Creating an Array of HashSet size
    String[] array = new String[hashset.size()];
    // Converting HashSet to Array using toArray() method
    hashset.toArray(array);
    //Showing Array elements
    System.out.println("Array contains :");
    for(String str : array){
        System.out.println(str);
    }
  }
 }


Output
HashSet contains :[Apple, Pear, Papaya, Orange, Banana]
Array contains :
Apple
Pear
Papaya
Orange
Banana



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry