Java Set to Array

Java Set to Array

In this post, we will learn java set to array conversion.

There are many ways to convert set to an array.


1. Using Java 8’s Stream

If you are using Java 8, I would recommend using Java 8 Stream.

Output

[John, Martin, Mary]

2. Using toArray()

We can directly call toArray() method on set object for java set to array conversion.

Output

[John, Martin, Mary]

3. Using toArray(IntFunction) [Java 11]

You can use Set#toArray(IntFunction<T[]>) method which takes IntFunction as generator

Output

[John, Martin, Mary]

4. Using System.arraycopy()

We can use System.arraycopy() for java set to array conversion.

Output

[John, Martin, Mary]

5. Using Arrays.copyOf

We can use Arrays.copyOf() for java set to array conversion.

Here, Array.copyOf takes 3 parameters

Output

[John, Martin, Mary]

6. Using simple iteration

Iterate through set and put the value in array manually.

Output

[John, Martin, Mary]

7. Using Guava library

There are two ways to convert set to array using guava library.

7.1 Using FluentIterable

FluentIterable class provide similar functionality to Java 8’s Stream. It takes iterable set and returns an array which contains all the elements from fluent iterable.

Output

[John, Martin, Mary]

7.2 Using Iterables

Iterables class provides toArray method which takes set and newType as input and return array contains iterable’s elements.

Output

[John, Martin, Mary]

That’s all about Java set to array.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *