How to convert List<Integer> to int[] in Java?

unknown picture unknown · Jun 6, 2009 · Viewed 508.8k times · Source

This is similar to this question: How to convert int[] to Integer[] in Java?

I'm new to Java. How can i convert a List<Integer> to int[] in Java? I'm confused because List.toArray() actually returns an Object[], which can be cast to nether Integer[] or int[].

Right now I'm using a loop to do so:

int[] toIntArray(List<Integer> list){
  int[] ret = new int[list.size()];
  for(int i = 0;i < ret.length;i++)
    ret[i] = list.get(i);
  return ret;
}

I'm sure there's a better way to do this.

Answer

Pshemo picture Pshemo · May 30, 2014

No one mentioned yet streams added in Java 8 so here it goes:

int[] array = list.stream().mapToInt(i->i).toArray();

Thought process:

  • simple Stream#toArray returns Object[], so it is not what we want. Also Stream#toArray(IntFunction<A[]> generator) doesn't do what we want because generic type A can't represent primitive int
  • so it would be nice to have some stream which could handle primitive type int instead of wrapper Integer, because its toArray method will most likely also return int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). And fortunately Java 8 has such stream which is IntStream
  • so now only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream()) to that shiny IntStream. Here Stream#mapToInt(ToIntFunction<? super T> mapper) method comes to a rescue. All we need to do is pass to it mapping from Integer to int. We could use something like Integer#getValue which returns int like :

    mapToInt( (Integer i) -> i.intValue() )  
    

    (or if someone prefers mapToInt(Integer::intValue) )

    but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int (lambda in mapToInt is implementation of ToIntFunction interface which expects body for int applyAsInt(T value) method which is expected to return int).

    So we can simply write

    mapToInt((Integer i)->i)
    

    Also since Integer type in (Integer i) can be inferred by compiler because List<Integer>#stream() returns Stream<Integer> we can also skip it which leaves us with

    mapToInt(i -> i)