DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on • Updated 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();

Oldest 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.