How Can I Convert an Integer List to an int Array in Java?

Hello Friends Today, through this tutorial, I will tell you how to convert an Integer List to an int array in Java Program?

Here are two primary approaches to convert an Integer List to an int array in Java.

1. Using the `toArray()` method with `int[]` as a parameter.

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
// Convert to int array explicitly
int[] intArray = integerList.stream().mapToInt(Integer::intValue).toArray();
// Alternatively, use toArray() with a pre-allocated array
int[] intArray2 = integerList.toArray(new int[integerList.size()]);

Explanation:-

1. This method directly calls `toArray()` on the `List` object, passing a new `int` array as an argument.
2. Java handles the conversion implicitly, filling the array with `int` values from the `Integer` objects.
3. It’s concise and efficient for smaller lists.

2. Using a for-each loop.

List<Integer> integerList = Arrays.asList(10, 20, 30);
int[] intArray = new int[integerList.size()];
int i = 0;
for (Integer num : integerList) {
intArray[i++] = num.intValue();
}

Explanation:-

1. This approach iterates through the list, manually copying each `Integer` value to its corresponding position in the `int` array using `intValue()`.
2. It offers more control over the conversion process and might be preferable for customization.