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
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)
A very simple one-line solution is:
Integer[] i = arrlist.stream().toArray(Integer[]::new);
Arrays.setAll() will work for most scenarios:
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;
}
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;
}
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;
}
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;
}
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());
}
Google Guava provides a neat way to do this by calling Ints.toArray.
List<Integer> list = ...;
int[] values = Ints.toArray(list);
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);
access arr
like normal int[]
.