41

What's the best way to convert HashSet<String> to String[]?

1
  • Remember a HashSet does not have a guaranteed order, so you won't know what order the array will be in. Commented Nov 14, 2020 at 5:18

3 Answers 3

104
set.toArray(new String[set.size()]);
Sign up to request clarification or add additional context in comments.

3 Comments

This is the best way to do it (+1)
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.
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".
5

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

0

The JB Nizet's answer is correct. In Java 15, the better answer is:

set.toArray(new String[0]); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.