Can you convert a list to an array?

There is no easy way to convert an array to a list in Java, but you can easily convert a list into an array by calling thetoArray[] method, which List inherits from theCollection interface. If you solely rely on core JDK, then the only way to convert an array to a list is by looping over the array and populating the list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there are many utility classes to convert list to array and vice-versa, as shown in this tutorial. If you are working on a Java application, you will often need to convert between list and array.

A list is nothing but a dynamic array that knows how to re-size itself when it gets full or gets close to full. List uses load factor to decide when to re-size, the default value of its is 0.75. When they re-size, the list usually doubles their slots e.g. goes from 16 to 32, etc.

You can find these nifty details in their implementation classes e.g. ArrayList is one of the popular lists in Java which provides order and random access.

If you want to truly master the Java Collection framework, then you must read the Java Generics and Collection book, written by Maurice Naftaline, and one of the must-read books to become an expert on the Java Collections framework.



Array to List in Java - Example

You can use advanced for loop or classical for loop to loop over the array and add each object into a list using add[] method, this is not a bad approach and you can easily write your own utility method say ArrayUtils.toList[] to encapsulate the logic.

Though you need to be aware to provide several overloaded methods for different types of array e.g. byte[], int[], short[], long[], float[], double[], char[], boolean[] and even object[]. This is cumbersome and that's why it's better to use a common utility library like Guava or Apache commons, which provides these kinds of handy methods right from the box.

Here is how you convert an int array to a List of integers in Java :
public static List toIntegerList[int[] intArray] { List result = new ArrayList[intArray.length]; for [int i : intArray] { result.add[i]; } return result; }Similarly, you need to write other list conversion methods to convert an array of boolean, byte, short, char, long, float, double, or object into the corresponding List in Java.



List to Array in Java - Example

Converting a list to an array is a cakewalk, all you need to do is call the toArray[] method to get all items of a list inside an array. This method is overloaded too, the one which doesn't take any parameter returns an Object[] but if you want an array of a particular type, you can use toArray[T[]] which returns all elements of the array with the type you specified.

It also returns elements in the order they are stored in a list. If the array is not big enough to store all elements another array with sufficient size is created and returned. Just remember that you cannot convert List to a primitive array with this method, the only way to do this is iterating over List and converting Integer to int using auto-boxing and storing them into an array.

Here is one example of converting a List of String to an array of String in Java :
List movies = Arrays.asList["Captain America", "Avatar", "Harry Potter"]; String[] arrayOfMovies = new String[movies.size[]]; movies.toArray[arrayOfMovies]; System.out.println["list of String : " + movies]; System.out.println["array of String : " + Arrays.toString[arrayOfMovies]]; Output : list of String : [Captain America, Avatar, Harry Potter] array of String : [Captain America, Avatar, Harry Potter]
You can see that array also contains the String in exactly the same order they were in List.



Java Program to convert list to array and vice-versa

Here is our sample program to demonstrate how to convert list to array and array to list easily in Java without using any third-party library like Apache Commons Collections or Google Guava.

package dto; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Java program to convert a list to array and vice-versa. * * @author WINDOWS 8 * */ public class ListToArrayDemo { public static void main[String args[]] { // let's create a list first List numbers = Arrays.asList[1, 2, 3, 4, 5, 6, 7]; System.out.println["list : " + numbers]; // let's first see how easy it is to convert a list to array // just call Collection.toArray[] method // You must pass an Integer[], int[] will not work int[] ints = new int[numbers.size[]]; // numbers.toArray[ints]; // compile time error expecting Integer[], // got // int[] Integer[] integers = new Integer[numbers.size[]]; numbers.toArray[integers]; System.out.println["array converted from list : " + Arrays.toString[integers]]; // now let's convert an array to a list in Java String[] languages = { "Java", "Perl", "Lisp", "JavaScript", "Python" }; System.out.println["array : " + Arrays.toString[languages]]; List fromArray = new ArrayList[languages.length]; for [String str : languages] { fromArray.add[str]; } System.out.println["array to list : " + fromArray]; // You can also create utility methods to convert array to list // but you need to create total of 9 method, much like various // println[] method, one for each primitive type and one for // all kind of object[]. I have created two of them to // show you how to create them, let's see how to use them // now. List names = toList[new String[]{"John", "Mohan", "Mary"}]; System.out.println["list from array in Java : " + names]; List primes = toIntegerList[new int[]{2, 3, 5, 7}]; System.out.println["list of Integer from an array of int : " + primes]; } /* * Static utility method to convert int[] to List */ public static List toIntegerList[int[] intArray] { List result = new ArrayList[intArray.length]; for [int i : intArray] { result.add[i]; } return result; } /* * Static utility method to convert T[] to List You can use this method * to convert any object[] to List

Chủ Đề