What's the best way to convert HashSet<String>
to String[]
?
There are two ways of converting HashSet to the array:Traverse through the HashSet and add every element to the array. To convert a HashSet into an array in java, we can use the function of toArray().
In order to convert a HashSet to Arraylist, we need is to use ArrayList constructor and pass the HashSet instance as a constructor argument. It will copy all elements from HashSet to the newly created ArrayList.
set.toArray(new String[set.size()]);
Answer of JB Nizet is correct, but in case you did this to transform to a CSV like string, with Java 8 you can now do:
Set<String> mySet = new HashSet<>(Arrays.asList("a", "b", "c"));
System.out.println(String.join(", ", mySet));
Output is: a, b, c
This allows to bypass array notation (the []
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With