While developing Java applications I have to convert ArrayList to Array lots of time. This is a very simple task and does not need any iterations, but I have seen most of the developers end up in iterating the list to create the array. So I thought of sharing this piece of code which converts ArrayList to Array in a single line.
ArrayList class has a method toArray() which can be used to convert to Array and here in this example we are using the same method.
Java Code to Convert ArrayList to Array
package com.lessonslab.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConvertArrayListToArray
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
list.add("Test4");
//toArray() adjusts the size automatically
//So you just need to initialize it with 0
String[] array = list.toArray(new String[0]);
//Print the array
System.out.println(Arrays.toString(array));
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ConvertArrayListToArray
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
list.add("Test4");
//toArray() adjusts the size automatically
//So you just need to initialize it with 0
String[] array = list.toArray(new String[0]);
//Print the array
System.out.println(Arrays.toString(array));
}
}
Output
[Test1, Test2, Test3, Test4]
To Generalise: To convert ArrayList of any class to Array use the below code. Just replace T with the class you want to create arrays.
T[] array = list.toArray(new T[0]);
This code will work for any kind of ArrayLists.
The post How to Convert ArrayList to Array in Java? appeared first on Jafaloo - The Tech Blog.