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
Java 8:
int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
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...
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;
}
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));
}
}
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;
}