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

后端 未结 8 1896
既然无缘
既然无缘 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:41

    You can just use Guava's:

    Ints.toArray(Collection<? extends Number> collection)
    
    0 讨论(0)
  • 2020-12-01 09:42

    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.

    0 讨论(0)
  • 2020-12-01 09:48

    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.

    0 讨论(0)
  • 2020-12-01 09:56

    You can convert a Set<Integer> to Integer[] even without Apache Utils:

    Set<Integer> myset = new HashSet<Integer>();
    Integer[] array = myset.toArray(new Integer[0]);
    

    However, if you need int[] you have to iterate over the set.

    0 讨论(0)
  • 2020-12-01 09:58

    Nope; you've got to iterate over them. Sorry.

    0 讨论(0)
  • 2020-12-01 09:58

    You could also use the toArray(T[] contents) variant of the toArray() method. Create an empty array of ints of the same size as the HashSet, and then pass it to the toArray() method:

    Integer[] myarray = new Integer[hashset.size()];
    doSomething(hashset.toArray(myarray));
    

    You'd have to change the doSomething() function to accept an Integer[] array instead of int[]. If that is not feasible, you'd have convert the array of values returned by toArray to int[].

    0 讨论(0)
提交回复
热议问题