How can I convert List<Integer> to int[] in Java?
You can use the toArray() method of the List interface to convert a List<Integer> to an int[] in Java.
To convert a List<Integer> to a primitive int[] in Java, the most idiomatic approach is using the Stream API. The List.toArray() method only returns object arrays (e.g., Integer[]), not primitive arrays. Here's the correct example:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = list.stream().mapToInt(i -> i).toArray();Alternatively, you can use the List.toArray(T[] a) method, which returns an Integer[] containing all of the elements in the list in proper sequence (from first to last element). Note that this does not directly produce a primitive int[]:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Integer[] objectArray = list.toArray(new Integer[0]);I hope this helps! Let me know if you have any other questions.