How to convert a HashSet to an array in Java
The perfect way to get an array from a HashSet is the use of the toArray(). This method is accessible by all data collections (ArrayList, HashMap, TreeSet, etc.). For more information, feel free to read the article How to convert ArrayList to Array.
In the following example, we create a HashSet of the generic type String, then we create an array of type String and copy the elements into the new array by calling the function hashset.toArray(array).
import java.util.HashSet;Output:
public class ToArray{
public static void main(String[] args) {
// Create a HashSet
HashSeths = new HashSet ();
//fill the elements
hs.add("E1");
hs.add("E2");
hs.add("E3");
hs.add("E4");
hs.add("E5");
// display
System.out.println("HashSet: "+ hs);
// create array
String[] array = new String[hs.size()];
hs.toArray(array);
// array display
System.out.print("array: ");
for(String e: array){
System.out.print(e+" ");
}
}
}
HashSet: [E2, E1, E4, E3, E5]
array: E2 E1 E4 E3 E5