Convert list to array in Java

Convert list to array in Java

In Java, you can convert a list to an array by using several methods, depending on your requirements. Here are a couple of common ways to do this:

Method 1: Using toArray() method You can use the toArray() method provided by the List interface to convert a list to an array. Here's an example:

import java.util.ArrayList; import java.util.List; public class ListToArrayExample { public static void main(String[] args) { List<String> myList = new ArrayList<>(); myList.add("Hello"); myList.add("World"); myList.add("Java"); // Convert the list to an array of strings String[] myArray = myList.toArray(new String[0]); // Print the elements of the array for (String element : myArray) { System.out.println(element); } } } 

In this example, myList.toArray(new String[0]) converts the myList to an array of strings. You can replace new String[0] with an array of the desired type if you want to specify the type of the resulting array.

Method 2: Using Java Streams You can also use Java Streams to convert a list to an array. Here's an example:

import java.util.ArrayList; import java.util.List; public class ListToArrayExample { public static void main(String[] args) { List<String> myList = new ArrayList<>(); myList.add("Hello"); myList.add("World"); myList.add("Java"); // Convert the list to an array of strings using Java Streams String[] myArray = myList.stream().toArray(String[]::new); // Print the elements of the array for (String element : myArray) { System.out.println(element); } } } 

In this example, myList.stream().toArray(String[]::new) converts the myList to an array of strings using Java Streams.

Choose the method that best fits your needs and coding style.


More Tags

postdata directx iframe touchpad utc cache-control dependencies kubectl cosine-similarity activexobject

More Java Questions

More Stoichiometry Calculators

More Tax and Salary Calculators

More Animal pregnancy Calculators

More Genetics Calculators