Converting List<String> to String[] in Java

JavaType Conversion

Java Problem Overview


How do I convert a list of String into an array? The following code returns an error.

public static void main(String[] args) {
	List<String> strlist = new ArrayList<String>();
	strlist.add("sdfs1");
	strlist.add("sdfs2");
	String[] strarray = (String[]) strlist.toArray();		
	System.out.println(strarray);
}

Error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
	at test.main(test.java:10)

Java Solutions


Solution 1 - Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

Solution 2 - Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

Solution 3 - Java

List.toArray() necessarily returns an array of Object. To get an array of String, you need to use the casting syntax:

String[] strarray = strlist.toArray(new String[0]);

See the javadoc for java.util.List for more.

Solution 4 - Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

Solution 5 - Java

hope this can help someone out there:

List list = ..;

String [] stringArray = list.toArray(new String[list.size()]);

great answer from here: https://stackoverflow.com/a/4042464/1547266

Solution 6 - Java

String[] strarray = strlist.toArray(new String[0]);

if u want List convert to string use StringUtils.join(slist, '\n');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristianView Question on Stackoverflow
Solution 1 - JavajjujumaView Answer on Stackoverflow
Solution 2 - JavaPaulView Answer on Stackoverflow
Solution 3 - JavacrazyscotView Answer on Stackoverflow
Solution 4 - JavadfaView Answer on Stackoverflow
Solution 5 - JavaArthurView Answer on Stackoverflow
Solution 6 - JavaphilView Answer on Stackoverflow