📅  最后修改于: 2023-12-03 15:01:31.317000             🧑  作者: Mango
In Java, converting a list to an array can be a common task. Fortunately, the Java API provides several methods to make this process quite easy.
The easiest way to convert a list to an array is to use the toArray()
method provided by the List
interface. This method returns an array containing all of the elements in the list in the correct order.
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("orange");
String[] array = list.toArray(new String[0]);
In this example, we create a List
of strings, add three elements to it, and then create a new array containing those same elements.
The toArray()
method takes an optional argument that is an array of the same type as the list. If the argument is large enough to hold all of the elements in the list, then the elements are copied into it. If the argument is not large enough, then a new array is created and returned.
Java 8 introduced the Stream
API, which provides several ways to convert a list to an array. Here's an example:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
In this example, we create a List
of integers, add three elements to it, and then use the stream()
method to convert the list to a Stream
. We then use the mapToInt()
method to convert each integer in the stream to its primitive int
value, and finally use the toArray()
method to convert the stream to an array.
Converting a list to an array in Java is a common task that can be accomplished using several different methods. Whether you prefer the simplicity of the toArray()
method or the versatility of the Stream
API, Java provides you with the tools you need to get the job done.