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

后端 未结 8 1956
既然无缘
既然无缘 2020-12-01 09:03

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

hashset.toArray();
         


        
8条回答
  •  再見小時候
    2020-12-01 09:48

    You can create an int[] from any Collection (including a HashSet) 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.

提交回复
热议问题