[java] How to convert an ArrayList containing Integers to primitive int array?

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()]);

This question is related to java arrays arraylist primitive-types

The answer is


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

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]

Google Guava

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

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

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)


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


Java 8:

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

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

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...


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

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

A very simple one-line solution is:

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

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.


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<>();

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


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

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.


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

access arr like normal int[].


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to primitive-types

how do I initialize a float to its max/min value? Setting Short Value Java How to convert an NSString into an NSNumber How to convert an ArrayList containing Integers to primitive int array?