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

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.