How to convert List to Array in Java

In this article, we will discuss how to convert List to Array in Java. So the first question arises in your mind is why you need to do such conversion. Well! many of the time when you call to some Java code it returns List object and you need to pass it to another method which requires an array of objects.

Recently while I invoked a web service request, it returned an object of a list of string. Further, I need to pass the list of string to some other service but it required an array of strings. Hence, I had to convert the list of string object to an array of string object and pass it to service.

Let us understand various methods of converting the list to array in Java.

Manual Conversion using for loop and get method of list

To convert List into Array, one of the simplest way is to loop the list to its size, retrieve each element from the list using get() method and assign it to an array. Let us demonstrate it using below code snippet.

import java.util.ArrayList;
import java.util.List;

public final class ListToArrayDemo {
	public static void main(String[] args) {
		List<String> lst = new ArrayList<String>();
		lst.add("Java");
		lst.add("List");
		lst.add("Array");
		int lstSize = lst.size();
		String arr[] = new String[lstSize];
		for(int count = 0; count < lstSize; count++){
			arr[count] = lst.get(count);
		}
		System.out.println("***Displaying the results in Array after conversion***");
		for(String output: arr)
		{
			System.out.println(output);
		}
	}
}

The output of above code snippet is

***Displaying the results in Array after conversion***
Java
List
Array

Conversion using toArray method

Using toArray method, you can convert List to Array in Java. The toArray() method is defined in each concrete List class and it is also defined in List interface.

Let us demonstrate how to convert List to Array in Java using toArray() method.

import java.util.ArrayList;
import java.util.List;

public final class ListToArrayDemo {
	public static void main(String[] args) {
		List<String> lst = new ArrayList<String>();
		lst.add("Java");
		lst.add("List");
		lst.add("Array");
		
		String arr[] = lst.toArray(new String[lst.size()]);
		System.out.println("***Displaying the results in Array after conversion using toArray method***");
		for(String output: arr)
		{
			System.out.println(output);
		}
	}
}

The output of above code snippet is

***Displaying the results in Array after conversion using toArray method***
Java
List
Array

In the above examples we demonstrated how to convert ArrayList of string into array of string. In the same way we can convert LinkedList and Vector to array in Java.

Article tagged as
Author
Author: Amit Gupta
Published On: 10/09/2015
Last revised On: 13/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media