Main Tutorials

Java – Convert ArrayList<String> to String[]

In the old days, we can use list.toArray(new String[0]) to convert a ArrayList<String> into a String[]

StringArrayExample.java

package com.mkyong;

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

public class StringArrayExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        list.add("A");
        list.add("B");
        list.add("C");

        // default, returns Object[], not what we want,
        // Object[] objects = list.toArray();

        // all jdk
        String[] str = list.toArray(new String[0]);

        for (String s : str) {
            System.out.println(s);
        }


    }

}

Output


A
B
C

For Java 8, we can do like this :


	// Java 8
	String[] str = list.stream().toArray(String[]::new);

For Java 9, we have a new way to create a List


	// Java 9
	List<String> list = List.of("A", "B", "C");

For Java 11, we can do the conversion like this :


	// Java 9
	List<String> list = List.of("A", "B", "C");
	
	// Java 11
    String[] str = list.toArray(String[]::new);

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments