How can I convert a Java HashSet<Integer> to a primitive int array? How can I convert a Java HashSet<Integer> to a primitive int array? arrays arrays

How can I convert a Java HashSet<Integer> 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.


Apache's ArrayUtils has this (it still iterates behind the scenes):

doSomething(ArrayUtils.toPrimitive(hashset.toArray()));

They're always a good place to check for things like this.


public int[] toInt(Set<Integer> set) {  int[] a = new int[set.size()];  int i = 0;  for (Integer val : set) a[i++] = val;  return a;}

Now that I wrote the code for you it's not that manual anymore, is it? ;)