454

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()]);
3
  • 3
    If you don't need primitive ints, you can use: List<Integer> x = new ArrayList<Integer>(); Integer[] n = x.toArray(new Integer[0]); Commented Jun 10, 2015 at 20:07
  • Possible duplicate of Converting an array of objects to an array of their primitive types Commented Oct 23, 2018 at 20:38
  • 2
    @cellepo That question is about converting between an Object and primitive array, this is about converting between an ArrayList and primitive array Commented Jul 7, 2020 at 14:47

20 Answers 20

426

If you are using 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 the int value hold by each Integer object (done automatically since Java 5)
  • getting the array of int by calling toArray

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I see this can be used for double types; are there no equivalent for float types?
266

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;
}

3 Comments

It 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).
You 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;
much easier now in Java8: integers.stream().mapToInt(Integer::valueOf).toArray
87

Google Guava

Google Guava provides a neat way to do this by calling Ints.toArray.

List<Integer> list = ...;
int[] values = Ints.toArray(list);

Comments

68

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.

5 Comments

Note 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.
I 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[])
@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.
Waht is the purpose of new Integer[0]?
@AdamHughes I believe it is to give a hint to toArray of which type of array to create
44

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;
}

Comments

11

Arrays.setAll()

    List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
    int[] n = new int[x.size()];
    Arrays.setAll(n, x::get);

    System.out.println("Array of primitive ints: " + Arrays.toString(n));

Output:

Array of primitive ints: [7, 9, 13]

The same works for an array of long or double, but not for arrays of boolean, char, byte, short or float. If you’ve got a really huge list, there’s even a parallelSetAll method that you may use instead.

To me this is good and elgant enough that I wouldn’t want to get an external library nor use streams for it.

Documentation link: Arrays.setAll(int[], IntUnaryOperator)

Comments

11

Java 8:

int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();

Comments

7

using Dollar should be quite simple:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

I'm planning to improve the DSL in order to remove the intermediate toArray() call

Comments

7

This works nice for me :)

Found at https://www.techiedelight.com/convert-list-integer-array-int/

import java.util.Arrays;
import java.util.List;

class ListUtil
{
    // Program to convert list of integer to array of int in Java
    public static void main(String args[])
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        int[] primitive = list.stream()
                            .mapToInt(Integer::intValue)
                            .toArray();

        System.out.println(Arrays.toString(primitive));
    }
}

Comments

7

Arrays.setAll() will work for most scenarios:

  1. Integer List to primitive int array:

    public static int[] convert(final List<Integer> list)
    {
       final int[] out = new int[list.size()];
       Arrays.setAll(out, list::get);
       return out;
    }
    
  2. Integer List (made of Strings) to primitive int array:

    public static int[] convert(final List<String> list)
    {
       final int[] out = new int[list.size()];
       Arrays.setAll(out, i -> Integer.parseInt(list.get(i)));
       return out;
    }
    
  3. Integer array to primitive int array:

    public static int[] convert(final Integer[] array)
    {
       final int[] out = new int[array.length];
       Arrays.setAll(out, i -> array[i]);
       return out;
    }
    
  4. Primitive int array to Integer array:

    public static Integer[] convert(final int[] array)
    {
       final Integer[] out = new Integer[array.length];
       Arrays.setAll(out, i -> array[i]);
       return out;
    }
    

Comments

4

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

2 Comments

I 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
Agreed with @PeterKriens. If anything, the fault is in Java for not supporting simple conversions like this in its standard data types
4

Java 8

int[] array = list.stream().mapToInt(i->i).toArray();

OR 

int[] array = list.stream().mapToInt(Integer::intValue).toArray();

1 Comment

Your answer is a duplicate of this one. Please delete your post and try to avoid doing that in the future.
3

If you're using Eclipse Collections, you can use the collectInt() method to switch from an object container to a primitive int container.

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
  ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

Assert.assertArrayEquals(
  new int[]{1, 2, 3, 4, 5},
  Lists.mutable.with(1, 2, 3, 4, 5)
    .collectInt(i -> i).toArray());

Note: I am a committer for Eclipse collections.

Comments

2

You can simply copy it to an array:

int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i);
}

Not too fancy; but, hey, it works...

Comments

1

Next lines you can find convertion from int[] -> List -> int[]

   private static int[] convert(int[] arr) {
        List<Integer> myList=new ArrayList<Integer>();
        for(int number:arr){
               myList.add(number);
            }
        }
        int[] myArray=new int[myList.size()];
        for(int i=0;i<myList.size();i++){
           myArray[i]=myList.get(i);
        }
        return myArray;
    }

Comments

0

Don't use java stream for this task if time is critical for your task
It is slower than using for-each loop. Use the same as:

    List<Integer> modes = new ArrayList<>();
    int[] m = new int[modes.size()];
    for (int i = 0; i < m.length; i++) {
        m[i] = modes.get(i);
    }

You can measure it with jmh

Comments

-1

This code segment is working for me, try this:

Integer[] arr = x.toArray(new Integer[x.size()]);

Worth to mention ArrayList should be declared like this:

ArrayList<Integer> list = new ArrayList<>();

2 Comments

Hello just a gentle reminder that OP wants a primitive array not an Object array.
Primitive int not wrapper Integer!
-1

A very simple one-line solution is:

Integer[] i = arrlist.stream().toArray(Integer[]::new);

1 Comment

op said primitive array meaning int[] not the Integer[] wrapper object, lol
-5
   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }

2 Comments

This answer does not work, it returns an array with a single element instead of multiple elements.
Why 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?
-8
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arr like normal int[].

1 Comment

this does not answer the question, the question was about converting to primitive type (int)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.