开发者

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());


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.


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.


Try this. Using java 8.

    Set<Integer> set = new HashSet<>();
    set.add(43);
    set.add(423);
    set.add(11);
    set.add(44);
    set.add(56);
    set.add(422);
    set.add(34);
    int[] arr = set.stream().mapToInt(Integer::intValue).toArray();


Note: This answer is outdated, use Stream.mapToInt(..)

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

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


You can just use Guava's:

Ints.toArray(Collection<? extends Number> collection)


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜