How to convert ArrayList to String Array in Java

Learn different ways to convert ArrayList to string array in Java with examples.

1. Convert arraylist to array – List.toArray()

This is most basic way to convert an arraylist containing string values to a string array.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> arrayList = new ArrayList<>();

        arrayList.add("how");
        arrayList.add("to");
        arrayList.add("do");
        arrayList.add("in");
        arrayList.add("java");

        String[] strArray = arrayList.toArray(new String[arrayList.size()]);

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[how, to, do, in, java]

2. Convert arraylist to string array – Java 8 stream

If you are using Java 8 or later, you can use stream and collector to get the string array from arraylist.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> arrayList = new ArrayList<>();

        arrayList.add("how");
        arrayList.add("to");
        arrayList.add("do");
        arrayList.add("in");
        arrayList.add("java");

        String[] strArray = arrayList.stream().toArray(String[]::new);

        System.out.println(Arrays.toString(strArray));
    }
}

Program output.

[how, to, do, in, java]

3. Conclusion

There are other ways also for this conversion from arraylist to string array using libraries such as apache commons and google guava, but those solutions add unnecessary complexity without adding any value. You can skip those solutions and stick to basics.

My preferred way is to use Java 8 streams. Feel free to share what’s your preferred way.

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs
Arrays Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “How to convert ArrayList to String Array in Java”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.