Convert Set to Array in Java

In this post, we will see how to convert set to array in plain Java, Java 8 and with the help of Guava library.


1. Naive

Naive solution would be to iterate over the given set and copy each encountered element in the Integer array one by one.


2. Set.toArray()

Set interface provides toArray() method that returns an Object array containing the elements of the set.

The JVM doesn’t know the desired object type, so toArray() method returns an Object[]. We can pass a typed array to overloaded toArray(T[] a) function to let JVM know what your desired object type is.

We can also pass an empty array of specified type and JVM will allocate necessary memory:


3. Java 8

In Java 8, we can use Stream API to convert set to array. The idea is to convert given set to Stream using function and use Stream.toArray() method to return an array containing the elements of the stream. There are two ways to do so:

1. Streams + method reference

2. Streams + lambda expression


4. Guava Library


4.1. Using FluentIterable class –

FluentIterable is an expanded Iterable API that provides similar functionality as Java 8’s streams API.

We can get a fluent iterable that wraps iterable set and returns an array containing all of the elements from fluent iterable.


4.2. Using Iterables class –

Guava’s Iterables class also provides toArray() function that copies an iterable’s elements into an array.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of