How can I convert List to int[] in Java? [duplicate]

With streams added in Java 8 we can write code like:

int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();

Thought process:

  • The simple Stream#toArray returns an Object[] array, so it is not what we want. Also, Stream#toArray(IntFunction<A[]> generator) doesn’t do what we want, because the generic type A can’t represent the primitive type int

  • So it would be nice to have some stream which could handle the primitive type int instead of the wrapper Integer, because its toArray method will most likely also return an int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural here). And fortunately Java 8 has such a stream which is IntStream

  • So now the 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.

    Quick searching in documentation of Stream while looking for methods which return IntStream points us to our solution which is mapToInt(ToIntFunction<? super T> mapper) method. All we need to do is provide a mapping from Integer to int.

    Since ToIntFunction is functional interface we can provide its instance via lambda or method reference.

    Anyway to convert Integer to int we can use Integer#intValue so inside mapToInt we can write:

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

    (or some may prefer: mapToInt(Integer::intValue).)

    But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type int (the lambda used in mapToInt is an implementation of the ToIntFunction interface which expects as body a method of type: int applyAsInt(T value) which is expected to return an int).

    So we can simply write:

    mapToInt((Integer i)->i)
    

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

    mapToInt(i -> i)
    

Leave a Comment