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