EN
Java - convert ArrayList to array[]
0 points
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.
In this example, we are using the stream()
method which works in Java 8 and earlier versions.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));
8
9
String[] strings = arrayList.stream().toArray(String[]::new);
10
11
for (String string : strings) {
12
System.out.println(string);
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
a
2
b
3
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);
Here we use the generic version of the toArray method.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));
8
9
String[] strings = arrayList.toArray(new String[0]);
10
11
for (String string : strings) {
12
System.out.println(string);
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
a
2
b
3
c
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
List<String> arrayList = new ArrayList<>(Arrays.asList("a", "b", "c"));
8
9
String[] strings = arrayList.toArray(new String[arrayList.size()]);
10
11
for (String string : strings) {
12
System.out.println(string);
13
}
14
}
15
}
Output:
xxxxxxxxxx
1
a
2
b
3
c