How to convert List<Integer> to int[] in Java?
No one mentioned yet streams added in Java 8 so here it goes:
int[] array = list.stream().mapToInt(i->i).toArray();
//OR
//int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
simple
Stream#toArray
returnsObject[]
, so it is not what we want. AlsoStream#toArray(IntFunction<A[]> generator)
doesn't do what we want because generic typeA
can't represent primitiveint
so it would be nice to have some stream which could handle primitive type
int
instead of wrapperInteger
, because itstoArray
method will most likely also returnint[]
array (returning something else likeObject[]
or even boxedInteger[]
would be unnatural here). And fortunately Java 8 has such stream which isIntStream
so now only thing we need to figure out is how to convert our
Stream<Integer>
(which will be returned fromlist.stream()
) to that shinyIntStream
. HereStream#mapToInt(ToIntFunction<? super T> mapper)
method comes to a rescue. All we need to do is pass to it mapping fromInteger
toint
. We could use something likeInteger#intValue
which returnsint
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)
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).
In addition to Commons Lang, you can do this with Guava's method Ints.toArray(Collection<Integer> collection)
:
List<Integer> list = ...
int[] ints = Ints.toArray(list);
This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself.