How to convert List<Integer> to int[] in Java? [duplicate]
Solution 1:
No one mentioned yet streams added in Java 8 so here it goes:
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
-
The simple
Stream#toArray
returns anObject[]
array, so it is not what we want. Also,Stream#toArray(IntFunction<A[]> generator)
doesn't do what we want because the generic typeA
can't represent the primitive typeint
-
So it would be nice to have some stream which could handle the primitive type
int
instead of the wrapperInteger
, because itstoArray
method will most likely also return anint[]
array (returning something else likeObject[]
or even boxedInteger[]
would be unnatural here). And fortunately Java 8 has such a stream which isIntStream
-
So now the only thing we need to figure out is how to convert our
Stream<Integer>
(which will be returned fromlist.stream()
) to that shinyIntStream
. Here theStream#mapToInt(ToIntFunction<? super T> mapper)
method comes to the rescue. All we need to do is pass it a mapping fromInteger
toint
.We could use something like
Integer#intValue
which returns anint
as shown below: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 inmapToInt
is an implementation of theToIntFunction
interface which expects as body a method of type:int applyAsInt(T value)
which is expected to return anint
).So we can simply write:
mapToInt((Integer i)->i)
Also, since the
Integer
type in(Integer i)
can be inferred by the compiler becauseList<Integer>#stream()
returns aStream<Integer>
, we can also skip it which leaves us withmapToInt(i -> i)
Solution 2:
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
-
List<T>.toArray
won't work because there's no conversion fromInteger
toint
- You can't use
int
as a type argument for generics, so it would have to be anint
-specific method (or one which used reflection to do nasty trickery).
I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the Arrays
class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).