How to convert an ArrayList containing Integers to primitive int array?
Solution 1
You can convert, but I don't think there's anything built in to do it automatically:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
(Note that this will throw a NullPointerException if either integers
or any element within it is null
.)
EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList
:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
Solution 2
If you are using java-8 there's also another way to do this.
int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:
- getting a
Stream<Integer>
from the list - obtaining an
IntStream
by mapping each element to itself (identity function), unboxing theint
value hold by eachInteger
object (done automatically since Java 5) - getting the array of
int
by callingtoArray
You could also explicitly call intValue
via a method reference, i.e:
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
It's also worth mentioning that you could get a NullPointerException
if you have any null
reference in the list. This could be easily avoided by adding a filtering condition to the stream pipeline like this:
//.filter(Objects::nonNull) also works
int[] arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray();
Example:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
int[] arr = list.stream().mapToInt(i -> i).toArray(); //[1, 2, 3, 4]
list.set(1, null); //[1, null, 3, 4]
arr = list.stream().filter(i -> i != null).mapToInt(i -> i).toArray(); //[1, 3, 4]
Solution 3
Google Guava
Google Guava provides a neat way to do this by calling Ints.toArray
.
List<Integer> list = ...;
int[] values = Ints.toArray(list);
Solution 4
Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.
import org.apache.commons.lang.ArrayUtils;
...
List<Integer> list = new ArrayList<Integer>();
list.add(new Integer(1));
list.add(new Integer(2));
int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));
However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.
Solution 5
I believe iterating using the List's iterator is a better idea, as list.get(i)
can have poor performance depending on the List implementation:
private int[] buildIntArray(List<Integer> integers) {
int[] ints = new int[integers.size()];
int i = 0;
for (Integer n : integers) {
ints[i++] = n;
}
return ints;
}
Snehal
Updated on April 27, 2021Comments
-
Snehal about 3 years
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()]);
-
paraquat over 13 yearsNote that this approach will make two complete copies of the sequence: one Integer[] created by toArray, and one int[] created inside toPrimitive. The other answer from Jon only creates and fills one array. Something to consider if you have large lists, and performance is important.
-
Peter Kriens over 13 yearsI do agree with the previous commenter. Not only do you drag in Apache Commons, but it easily translates into a large set of transitive dependencies that also need to be dragged in. Recently I could remove an amazing # of dependencies by replacing one line of code :-( Dependencies are costly and writing basic code like this is good practice
-
Matthew Willis about 13 yearsIt might be better to iterate using the List's iterator (with for each) so as to avoid performance hits on lists whose access is not O(1).
-
Asaf over 11 yearsthis does not answer the question, the question was about converting to primitive type (int)
-
Oskar Lund about 11 yearsI measured performance using ArrayUtils vs pure java and on small lists (<25 elements) pure java is more than 100 times faster. For 3k elements pure java is still almost 2 times faster... (ArrayList<Integer> --> int[])
-
Sean Connolly about 11 years@paraquat & Oskar Lund that is not actually correct. Yes, the code provided will create two arrays, but this approach does not. The problem in this code here is the use of a zero length array as the argument. The ArrayList.toArray source code shows that if the contents will fit, the original array will be used. I think in a fair comparison you'll find this method to be as efficient (if not more) and, of course, less code to maintain.
-
Sean Connolly about 11 yearsI think this'll be the answer for me - I'll take a library over a copy-paste function any day.. especially a library that a decent sized project likely already uses. I hope this answer gets more up-votes and visibility in the future.
-
Sean Connolly about 11 years
-
Mysticial about 11 yearsThis answer does not work, it returns an array with a single element instead of multiple elements.
-
gardarh over 10 yearsYou can also utilize the fact the ArrayList implements Iterable (via Collection inheritance) and do: for(int n : integer) { ret[counter++] = n; } ... and initialize int counter = 0;
-
Manish Patel over 8 yearsmuch easier now in Java8:
integers.stream().mapToInt(Integer::valueOf).toArray
-
Adam Hughes over 8 yearsWaht is the purpose of new Integer[0]?
-
Victor Zamanian over 8 yearsWhy use a StringBuffer? Why convert the Integer to a String and then to an Integer and then to an int and then to an Integer again? Why use an array with a single element in it, and why loop over that single-element array when it contains just one element? Why cast the Integers to Objects in the outer loop? There are so many questions here. Is @CodeMadness just a troll account?
-
code_dredd over 6 yearsI see this can be used for
double
types; are there no equivalent forfloat
types? -
OLIVER.KOO over 6 yearsHello just a gentle reminder that OP wants a primitive array not an Object array.
-
Bartzilla about 6 yearsPrimitive int not wrapper Integer!
-
Adam Hughes about 6 yearsAgreed with @PeterKriens. If anything, the fault is in Java for not supporting simple conversions like this in its standard data types
-
Eugene over 4 yearsSaw the benefit of Java 8 by you elaborate explanation.
-
Pranav A. about 4 yearsAnd this is why the Java 8+ Stream API is beautiful.
-
Nosrep almost 4 years@AdamHughes I believe it is to give a hint to
toArray
of which type of array to create -
luckyguy73 over 3 yearsop said primitive array meaning int[] not the Integer[] wrapper object, lol
-
Janez Kuhar about 3 yearsYour answer is a duplicate of this one. Please delete your post and try to avoid doing that in the future.
-
famfamfam over 2 yearshow to call "Ints"???