Skip to content

Convert Set (HashSet) to array example

Convert Set (HashSet) to array example shows how to convert Set to array in Java using various ways including the toArray method and Java stream.

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

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

1) Using the toArray method of the HashSet

This method returns an array containing all the elements of the collection. The type of the returned array is the same as that of the argument array.

The below given example shows how to convert HashSet of String to a String array.

Output

If the argument array is smaller in size than the set object, a new array of the same type is created, filled with the set elements and returned. If the argument array is bigger than the set, the array element that immediately comes after the set elements is set to null.

Output

As you can see from the output, the array element “4” is set to null in the array to mark the end of the set elements.

However, do not rely on the null array element to determine the boundary of the set elements as the set itself might contain the null elements as given below.

Output

Note: It is suggested to pass the argument array of the same size to the toArray method. If the array is smaller than the size of the HashSet, a new array needs to be created by JVM to fit the collection elements and thus may impact the performance.

2) Using Java 8 stream

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

Output:

This example is a part of the Java Array tutorial and Java HashSet tutorial.

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

About the author

Leave a Reply

Your email address will not be published.