Languages
[Edit]
EN

Java - convert ArrayList to array[]

0 points
Created by:
LionRanger
461

In this article, we would like to show you how to convert ArrayList to an array in Java.

Below are the most common ways to convert an ArrayList to a primitive list.

Solutions for Java 8

1. stream() method

In this example, we are using the stream() method which works in Java 8 and earlier versions.

import java.util.Arrays;
import java.util.List;

public class Example {

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));

        String[] strings = arrayList.stream().toArray(String[]::new);

        for (String string : strings) {
            System.out.println(string);
        }
    }
}

 Output: 

a
b
c

Note:

In Java 11 and higher versions we no longer need to use the stream() method - then the code will look like this: 
String[] strings = list.toArray(String[]::new);

2. List.toArray(new String[0])

Here we use the generic version of the toArray method. 

import java.util.Arrays;
import java.util.List;

public class Example {

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));

        String[] strings = arrayList.toArray(new String[0]);

        for (String string : strings) {
            System.out.println(string);
        }
    }
}

Output:

a
b
c

3. List.toArray(new String[arrayList.size()])

import java.util.Arrays;
import java.util.List;

public class Example {

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));

        String[] strings = arrayList.toArray(new String[arrayList.size()]);

        for (String string : strings) {
            System.out.println(string);
        }
    }
}

 Output: 

a
b
c

See also:

  1. toArray method - Java 8 docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join