Home >Java >javaTutorial >How to Efficiently Convert an ArrayList to a Primitive int Array in Java?

How to Efficiently Convert an ArrayList to a Primitive int Array in Java?

DDD
DDDOriginal
2024-12-15 07:46:13727browse

How to Efficiently Convert an ArrayList to a Primitive int Array in Java?

Converting ArrayList to Primitive int Array

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn