How To Convert List To Array In Java

Introduction

In this blog, you will learn how to convert a list to an array in java. There are several ways to convert a list to an array in java. Please look at the below example,

Example

import java.util.*;
class ListToArrayExample {
    public static void main(String args[]) {
        ArrayList < String > list = new ArrayList();
        list.add("Abhishek");
        list.add("Harshit");
        list.add("Shruti");
        list.add("Gaurav");
        list.add("Pranav");
        list.add("Arpit");
        list.add("Ishika");
        System.out.println("My List: " + list);
        System.out.println("***************************************************");
        System.out.println("String Array1:");
        // 1st Method
        String str1[] = new String[list.size()];
        for (int i = 0; i < str1.length; i++) {
            str1[i] = list.get(i);
        }
        // print string array
        for (int i = 0; i < str1.length; i++) {
            System.out.print(str1[i] + " ");
        }
        // 2nd Method 
        String str2[] = new String[list.size()];
        str2 = list.toArray(str2);
        // print string array
        System.out.println("\nString Array2:");
        for (int i = 0; i < str2.length; i++) {
            System.out.print(str1[i] + " ");
        }
    }
}

Output

 

Conclusion

In this blog, we have seen how to convert a list to an array in java. Thanks for reading and I hope you like it. If you have any suggestions or queries about this blog, please share your thoughts. You can read my other blog and articles by clicking here.

Happy learning, friends!

Next Recommended Reading Remove Duplicates From Array In Java