431

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()]);
Jonas
  • 121,568
  • 97
  • 310
  • 388
Snehal
  • 7,266
  • 2
  • 32
  • 42
  • 3
    If you don't need primitive ints, you can use: `List x = new ArrayList();` `Integer[] n = x.toArray(new Integer[0]);` – Evorlor Jun 10 '15 at 20:07
  • Possible duplicate of [Converting an array of objects to an array of their primitive types](https://stackoverflow.com/questions/564392/converting-an-array-of-objects-to-an-array-of-their-primitive-types) – cellepo Oct 23 '18 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 – Nosrep Jul 07 '20 at 14:47

19 Answers19

398

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]
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
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;
}
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 23
    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). – Matthew Apr 02 '11 at 20:52
  • 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; – gardarh Feb 14 '14 at 15:04
  • 15
    much easier now in Java8: `integers.stream().mapToInt(Integer::valueOf).toArray` – Manish Patel Oct 23 '15 at 21:18
87

Google Guava

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

List<Integer> list = ...;
int[] values = Ints.toArray(list);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Snehal
  • 7,266
  • 2
  • 32
  • 42
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.

Björn
  • 29,019
  • 9
  • 65
  • 81
  • 3
    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. – paraquat Oct 18 '10 at 18:48
  • 1
    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 --> int[]) – Oskar Lund Apr 04 '13 at 16:26
  • @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](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList.toArray%28java.lang.Object%5B%5D%29) 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 Apr 23 '13 at 12:10
  • PS: [a nice related post](http://stackoverflow.com/questions/174093/toarraynew-myclass0-or-toarraynew-myclassmylist-size) – Sean Connolly Apr 23 '13 at 12:20
  • 1
    Waht is the purpose of new Integer[0]? – Adam Hughes Jan 12 '16 at 15:13
  • @AdamHughes I believe it is to give a hint to `toArray` of which type of array to create – Nosrep Jul 07 '20 at 14:50
43

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;
}
AsksAnyway
  • 890
  • 1
  • 8
  • 21
Matthew
  • 44,826
  • 10
  • 98
  • 87
11

Java 8:

int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
EssaidiM
  • 7,924
  • 1
  • 18
  • 22
9

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)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
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

dfa
  • 114,442
  • 31
  • 189
  • 228
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));
    }
}
Miguel Carrillo
  • 327
  • 5
  • 7
6

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;
    }
    
PerracoLabs
  • 16,449
  • 15
  • 74
  • 127
5

Java 8

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

OR 

int[] array = list.stream().mapToInt(Integer::intValue).toArray();
Sneha Mule
  • 641
  • 8
  • 6
  • 1
    Your answer is a duplicate of [this one](https://stackoverflow.com/a/23688547/6367213). Please delete your post and try to avoid doing that in the future. – Janez Kuhar Apr 26 '21 at 17:15
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

nickb
  • 59,313
  • 13
  • 108
  • 143
Andrew F.
  • 85
  • 1
  • 9
    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 – Peter Kriens Oct 29 '10 at 14:45
  • 1
    Agreed with @PeterKriens. If anything, the fault is in Java for not supporting simple conversions like this in its standard data types – Adam Hughes Mar 04 '18 at 19:36
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.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
Craig P. Motlin
  • 26,452
  • 17
  • 99
  • 126
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...

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
sagiksp
  • 143
  • 1
  • 7
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;
    }
Sherlock
  • 11
  • 2
0

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<>();
ozkanpakdil
  • 3,199
  • 31
  • 48
-1

A very simple one-line solution is:

Integer[] i = arrlist.stream().toArray(Integer[]::new);
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
PramodG
  • 40
  • 1
-4
   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());
    }
  • 1
    This answer does not work, it returns an array with a single element instead of multiple elements. – Mysticial May 03 '13 at 08:15
  • 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? – Victor Zamanian Feb 10 '16 at 11:57
-7
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arr like normal int[].

axel22
  • 32,045
  • 9
  • 125
  • 137
snn
  • 9
  • 7
    this does not answer the question, the question was about converting to primitive type (int) – Asaf Oct 27 '12 at 23:21