Java List.toArray
Convert a list into an array of the required component type for an API that accepts arrays.
A simple example
List.toArray
- Start with List containing A and B
- Do this Convert to an array
- Result Array containing A and B
Syntax
names.toArray(String[]::new)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSend the badge roster to an older printer
A school stores its badge roster in a list, but the older printer driver accepts an array of names. The coordinator converts the roster before sending it to the printer in registration order.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var roster = List.of("Mira", "Sam");
String[] printJob = roster.toArray(String[]::new);
System.out.println(String.join(", ", printJob));
}
}
Mira, Sam
The generator creates a String array with one slot for each name in the roster.
Correct a print job without editing the roster
A receptionist needs an uppercase name on one replacement badge. The temporary print array can be changed while the master list keeps the student's usual spelling.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var roster = List.of("Mira");
String[] printJob = roster.toArray(String[]::new);
printJob[0] = "MIRA";
System.out.println(roster.get(0));
}
}
Mira
Replacing an element of the array does not replace the corresponding element of the list.
Load a lobby display
The gallery sends an ordered set of rooms to a display that accepts an array. Transfer the ordered entries to an array for the display. Which sequence will its positions contain?
What to watch for
The no-argument overload returns Object[]. Use the generator overload when the receiver needs a String[].