How can I convert a Java HashSet to a primitive int array?

You can create an int[] from any Collection<Integer> (including a HashSet<Integer>) using Java 8 streams:

int[] array = coll.stream().mapToInt(Number::intValue).toArray();

The library is still iterating over the collection (or other stream source) on your behalf, of course.

In addition to being concise and having no external library dependencies, streams also let you go parallel if you have a really big collection to copy.

Leave a Comment