W3docs

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

To convert an ArrayList containing Integer objects to a primitive int array in Java, you can use the toArray method and a casting operation.

To convert an ArrayList containing Integer objects to a primitive int array in Java, you can use the Stream API with mapToInt and toArray.

Here's an example of how you can do this:


import java.util.ArrayList;
import java.util.List;

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

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

This code creates an ArrayList containing three Integer objects, and then converts it to an int array using the stream, mapToInt, and toArray methods.

Alternatively, you can use a traditional loop to avoid stream overhead:


import java.util.ArrayList;
import java.util.List;

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
}

This approach produces the same result and can be more efficient for simple conversions.

I hope this helps! Let me know if you have any questions.