Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...