Dowemo
0 0 0 0


Question:

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.


Best Answer:


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, because its toArray method will most probably also return int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). And fortunately Java 8 has such stream: 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 mapToInt method comes to rescue. All we need to do is provide some mapping from Integer to int. We could use something like Integer#getValue which returns int:

    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)

    or simpler (since Integer i type can be inferred by compiler because List<Integer>#stream() returns Stream<Integer>)

    mapToInt(i -> i)




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs