Collections

Convert Set (HashSet) to array example

Convert Set (HashSet) to array example shows how to convert Set (HashSet) to array in Java. Example also shows how to convert Set (HashSet) to array using Java 8.

How to convert Set (HashSet) to array in Java?

There are a couple of ways using which you can convert Set (HashSet) to array in Java as given below.

1) Convert Set (HashSet) to array using toArray method of HashSet

To convert Set or HashSet to an array, use toArray method.

This method returns an array containing all the elements of the collection. Type of the returned array is same as that of the argument array. If the argument array is smaller in size, a new array of the same type is created and returned. If argument array is bigger than the collection, remaining elements of the array is filled with null values.

Example Code:

Output

Note:

It is suggested to pass the argument array of same size to toArray method. If the array is smaller in size, a new array has to be created by JVM to fit the collection elements and thus degrades the performance.

2) Convert Set (HashSet) to array using Java 8 stream

If you are using Java 8, you can create a stream from an array and then call toArray method to convert HashSet to array as given below.

Output:

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.