Home >Java >javaTutorial >How to Efficiently Convert an ArrayList to a Primitive int Array in Java?
Converting ArrayList
Attempting to convert an ArrayList containing Integer objects to a primitive int array using the code below will result in a compile-time error:
Java 8 Stream Conversion
In Java 8, a more efficient approach involves using the Stream API. Here's how it's done:
This code creates a stream from the list, maps each Integer object to its primitive int value using the Integer::intValue method reference, and then converts the IntStream to an int array using toArray().
Error Handling
If the list contains any null references, the above code will throw a NullPointerException. To avoid this, you can filter out any null values before mapping:
Example:
The above is the detailed content of How to Efficiently Convert an ArrayList to a Primitive int Array in Java?. For more information, please follow other related articles on the PHP Chinese website!