This post will discuss how to convert a set to an array in plain Java, Java 8, and the Guava library.

1. Naive solution

A naive solution is to iterate over the given set and copy each encountered element in the Integer array one by one.

 

 

2. Using Set.toArray() method

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

 

 

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

 

 

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

 

 

3. Using Java 8

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

⮚ Using Streams with method reference

 

 

⮚ Using Streams with lambda expression

 

 

4. Using Guava Library

⮚ Using FluentIterable class:

The FluentIterable is an expanded Iterable API that provides similar functionality as Java 8’s Stream. We can get a fluent iterable that wraps an iterable set and returns an array containing all the elements from the fluent iterable.

 

 

⮚ Using Iterables class:

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

 

 

That’s all about converting Set to array in Java.