Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from HashSet<String> to String[]

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

like image 969
Jack B. Avatar asked Mar 29 '11 15:03

Jack B.


People also ask

How do I convert a HashSet to an array?

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().

Can we convert HashSet to ArrayList?

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.


2 Answers

set.toArray(new String[set.size()]); 
like image 131
JB Nizet Avatar answered Sep 24 '22 06:09

JB Nizet


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 []).

like image 29
Christophe Roussy Avatar answered Sep 22 '22 06:09

Christophe Roussy