Introduction
This lab will guide you in converting an Integer List to an Int Array in Java. There are two ways of doing this - using the stream.mapToInt()
method or using the ArrayUtils.toPrimitive()
method.
This lab will guide you in converting an Integer List to an Int Array in Java. There are two ways of doing this - using the stream.mapToInt()
method or using the ArrayUtils.toPrimitive()
method.
To use the ArrayUtils.toPrimitive()
method, we need to import the org.apache.commons.lang3.ArrayUtils
package. Add the following imports at the beginning of your Java file:
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
Now, we will create an Integer List with a few values. Add the following code to create an Integer List:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
With the Integer List created in step 3, we can now convert it to an Int Array using the stream.mapToInt()
method. Add the following code block to your Java file:
int[] arr = list.stream().mapToInt(i -> i).toArray();
for (int val : arr) {
System.out.println(val);
}
Here, the stream.mapToInt()
method is called on the Integer List, converting it to an IntStream. The toArray()
method is then called on this IntStream to convert it to an Int Array.
To run the code in the terminal, compile the Java program by running javac IntegerListToIntArray.java
, followed by java IntegerListToIntArray
.
We can also convert the Integer List to an Int Array using the ArrayUtils.toPrimitive()
method. Add the following code block to your Java file to use this method:
int[] arr = ArrayUtils.toPrimitive(list.toArray(new Integer[list.size()]));
for (int val : arr) {
System.out.println("int primitive: " + val);
}
Here, the toArray()
method is called on the Integer List to convert it to an Object Array. This Object Array is then passed to the toPrimitive()
method, which returns an Int Array.
To run the code in the terminal, compile the Java program by running javac IntegerListToIntArray.java
, followed by java IntegerListToIntArray
.
In this lab, we learned how to convert an Integer List to an Int Array in Java. We explored two different methods to do so - using the stream.mapToInt()
method and the ArrayUtils.toPrimitive()
method - and provided sample code blocks to implement each one. By following these steps, you should now be able to convert an Integer List to an Int Array in your Java programs.