What's the best way to convert HashSet<String> to String[]?
3 Answers
set.toArray(new String[set.size()]);
3 Comments
Sean Patrick Floyd
This is the best way to do it (+1)
Roel Spilker
I would use set.toArray(new String[0]); or even set.toArray(EMPTY_STRING_ARRAY); The set.size() does not add any performance benefit but uses up mental space for the reader.
LuminousNutria
It is also possible to do
set.toArray(new String[]{}); in java 12. My IDE, IntelliJ, says "In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection".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 []).
Comments
The JB Nizet's answer is correct. In Java 15, the better answer is:
set.toArray(new String[0]);
HashSetdoes not have a guaranteed order, so you won't know what order the array will be in.