Java
Programming
Data Conversion
String Arrays
Set Collections

Convert a Set<String> to a String[] in Java

Codemia Knowledge Hub ·

To turn a Set<String> into a String[], call set.toArray(new String[0]). On Java 8 and later, set.stream().toArray(String[]::new) also works. You need this when an API expects an array, for performance reasons, or when the logic works on array data.

How Set<String> and String[] differ

  • A Set<String> holds no duplicates and has no guaranteed order, unless it is an ordered or sorted implementation such as LinkedHashSet or TreeSet. It is an interface in Java's Collections framework, with methods for set operations like union, intersection, and difference.
  • A String[] is a fixed-size array whose elements are accessed by index.

Method 1: toArray(new String[0])

toArray(T[] a) on the Set interface is the most direct way to convert a Set<String>:

java
1Set<String> stringSet = new HashSet<>();  
2stringSet.add("Hello");
3stringSet.add("World");
4
5String[] stringArray = stringSet.toArray(new String[0]);

The array argument tells the method what type of array to return. It does not need to match the set's size: if it is too small, a new array of the right size is created.

Method 2: the Stream API

The Stream API, introduced in Java 8, can also convert a Set<String> to a String[]:

java
1Set<String> stringSet = new HashSet<>();
2stringSet.add("Hello");
3stringSet.add("Java");
4
5String[] stringArray = stringSet.stream().toArray(String[]::new);

stream() creates a stream from the set, and toArray(String[]::new) collects it into a new String[] using a constructor reference.

Comparing the two

MethodDescriptionSyntax ComplexityPerformance
toArray(new)Utilizes the built-in toArray method of the collection.SimpleFaster for smaller sets
Stream APILeverages the Stream API for conversion.Moderately complexGood for large/complex operations

Either way gives you a String[] from a Set<String>; choose based on readability and your application's requirements.

Nulls, threads and element order

  • Null elements: any null in the Set<String> ends up in the array, so your code must handle it.
  • Thread safety: if other threads access the set concurrently, synchronize during the conversion.
  • Order: most sets do not keep element order, so the array order may be unpredictable. Use a LinkedHashSet if you need insertion order.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms