ArrayList to Array Conversion in Java
Swapnil Gupta

Swapnil Gupta @swapnilxi

About: Some Broken Lines of codes and a cup of coffee, that's pretty much it! I Speak and Love #Java!

Joined:
Jun 12, 2021

ArrayList to Array Conversion in Java

Publish Date: Dec 19 '22
0 1

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();

Comments 1 total

  • Sloan the DEV Moderator
    Sloan the DEV ModeratorDec 19, 2022

    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.

Add comment