DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on • Edited on

ArrayList to Array Conversion in Java

https://codeahoy.com/java/How-To-Convery-ArrayList-To-Array/

Method 1-

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    for (int i=0; i < ret.length; i++)
    {
        ret[i] = integers.get(i).intValue();
    }
    return ret;
}

Enter fullscreen mode Exit fullscreen mode

Method 2-

List<Integer> ans =  new ArrayList<Integer>();
int[] n = (int[])ans.toArray(int[ans.size()]);
Enter fullscreen mode Exit fullscreen mode

Method 3- using Steam
int[] arr = list.stream().mapToInt(i -> i).toArray();

(from stackoverflow)

If you are using java-8 there's also another way to do this.

int[] arr = list.stream().mapToInt(i -> i).toArray();
What it does is:

getting a Stream from the list
obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5)
getting the array of int by calling toArray
You could also explicitly call intValue via a method reference, i.e:

int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
sloan profile image
Sloan the DEV Moderator

Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.

If you choose to do so, you also have the option to add a canonical URL directly to your post.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay