How to convert an ArrayList containing Integers to primitive int array?

JavaArraysArraylistPrimitive Types

Java Problem Overview


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

Java Solutions


Solution 1 - Java

If you are using [tag: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 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]

Solution 2 - Java

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 3 - Java

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

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

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

Solution 6 - Java

Java 8:

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

Solution 7 - Java

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)

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

Java 8

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

OR 

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

Solution 16 - Java

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

Solution 17 - Java

A very simple one-line solution is:

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

Solution 18 - Java

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

Solution 19 - Java

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

access arr like normal int[].

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSnehalView Question on Stackoverflow
Solution 1 - JavaAlexis C.View Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaSnehalView Answer on Stackoverflow
Solution 4 - JavaBjörnView Answer on Stackoverflow
Solution 5 - JavaMatthew WillisView Answer on Stackoverflow
Solution 6 - JavaEssaidiMView Answer on Stackoverflow
Solution 7 - JavaOle V.V.View Answer on Stackoverflow
Solution 8 - JavadfaView Answer on Stackoverflow
Solution 9 - JavaMiguel CarrilloView Answer on Stackoverflow
Solution 10 - JavaPerracoLabsView Answer on Stackoverflow
Solution 11 - JavaAndrew F.View Answer on Stackoverflow
Solution 12 - JavaCraig P. MotlinView Answer on Stackoverflow
Solution 13 - JavasagikspView Answer on Stackoverflow
Solution 14 - JavaSherlockView Answer on Stackoverflow
Solution 15 - JavaSneha MuleView Answer on Stackoverflow
Solution 16 - JavaHarshan MorawakaView Answer on Stackoverflow
Solution 17 - JavaPramodGView Answer on Stackoverflow
Solution 18 - JavaCodeMadnessView Answer on Stackoverflow
Solution 19 - JavasnnView Answer on Stackoverflow