I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?
List<Integer> x = new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);
Best Answer
If you are using java-8 there's also another way to do this.
What it does is:
Stream<Integer>
from the listIntStream
by mapping each element to itself (identity function), unboxing theint
value hold by eachInteger
object (done automatically since Java 5)int
by callingtoArray
You could also explicitly call
intValue
via a method reference, i.e:It's also worth mentioning that you could get a
NullPointerException
if you have anynull
reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:Example: