Convert Java String List To Array

This article will show you two method that can convert a Java String List to String Array. Below is the Java example code. Please see the comments for detail explanation.

public class ConvertJavaStringListToArray {

	public static void main(String[] args) {
		
		List<String> arrayList = new ArrayList<String>();
		arrayList.add("Java");
		arrayList.add("C++");
		arrayList.add("MFC");
		arrayList.add("Python");
		arrayList.add("Perl");
		
		//String strArr[] = ConvertJavaStringListToArray.stringListToArray(arrayList);
		
		String strArr[] = ConvertJavaStringListToArray.stringListToArray1(arrayList);
		
		for(String str : strArr)
		{
			System.out.println(str);
		}

	}

	
	private static String[] stringListToArray(List<String> strList)
	{
		/* First convert the List to an object array. */
		Object objArr[] = strList.toArray();
		
		/* Use Arrays.copyOf method to translate the object array to string array. */
		String ret[] = Arrays.copyOf(objArr, objArr.length, String[].class);
		
		return ret;
	}
	
	private static String[] stringListToArray1(List<String> strList)
	{
		if(strList!=null)
		{
			/* Get the list size. */
			int size = strList.size();
			
			/* Define the return array with the size. */
			String retArr[] = new String[size];
			
			/* Loop in the list, add each string to the array. */
			for(int i=0; i<size; i++)
			{
				retArr[i] = strList.get(i);
			}
			
			return retArr;
			
		}else
		{
			String retArr[] = {};
			return retArr;
		}
	}
}

The Output

Java
C++
MFC
Python
Perl

Download “ConvertJavaStringListToArray.zip” ConvertJavaStringListToArray.zip – Downloaded 30 times – 750 B

(Visited 169 times, 1 visits today)
READ :   Java.util.ConcurrentModificationException Examples And Resolution

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.