Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got a HashSet<Integer> with a bunch of Integers in it. I want to turn it into an array, but calling

hashset.toArray(); 

returns an Object[]. Is there a better way to cast it to an array of int other than iterating through every element manually? I want to pass the array to

void doSomething(int[] arr) 

which won't accept the Object[] array, even if I try casting it like

doSomething((int[]) hashSet.toArray()); 
like image 802
jackbot Avatar asked Mar 15 '10 23:03

jackbot


People also ask

How do I convert a HashSet to an array?

There are two ways of converting HashSet to the array:Traverse through the HashSet and add every element to the array. To convert a HashSet into an array in java, we can use the function of toArray().

How do you convert a number to an int array?

int temp = test; ArrayList<Integer> array = new ArrayList<Integer>(); do{ array. add(temp % 10); temp /= 10; } while (temp > 0); This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].


2 Answers

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.

like image 54
Jeffrey Bosboom Avatar answered Oct 12 '22 23:10

Jeffrey Bosboom


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.

like image 33
Matthew Flaschen Avatar answered Oct 12 '22 23:10

Matthew Flaschen