We can use below solutions for converting ArrayList to Array in java.
Solution 1 : Convert arraylist to array using Java 8 Stream API.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.ArrayList; import java.util.Arrays; public class ArrayListToArray { public static void main(String[] args) { ArrayList<String> animalsList = new ArrayList<>(); animalsList.add("Cow"); animalsList.add("Dog"); animalsList.add("Lion"); animalsList.add("Panda"); animalsList.add("Walrus"); animalsList.add("Chimpanzee"); String[] animalsArray = animalsList.stream().toArray(String[]::new); System.out.println(Arrays.toString(animalsArray)); } } |
Output :
1 |
[Cow, Dog, Lion, Panda, Walrus, Chimpanzee] |
Solution 2 : Convert arraylist to array using List.toArray()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.ArrayList; import java.util.Arrays; public class ArrayListToArray { public static void main(String[] args) { ArrayList<String> employeesList = new ArrayList<>(); employeesList.add("manohar"); employeesList.add("suresh"); employeesList.add("ramana"); String[] employeesArray = employeesList.toArray(new String[arrayList.size()]); System.out.println(Arrays.toString(employeesArray)); } } |
Output :
1 |
[manohar, suresh, ramana] |