Conversion of ArrayList to Arrays in Java – 2 ways

In this article, we will discuss how to convert ArrayList to Arrays in different ways

 

1. Conversion of ArrayList to String Arrays using toArrays(); method

Steps :

  • Initialize ArrayList with sample values
  • Convert ArrayList to String[] Arrays using toArrays(); method, by passing to ArrayList‘s size
  • Print converted String[] Arrays in console using enhanced for-each loop

Method signature:

public Object toArrays();

ConvertArrayListToStringArrays.java

package in.bench.resources.collection;

import java.util.ArrayList;

public class ConvertArrayListToStringArrays {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Hollywood");
		al.add("Bollywood");
		al.add("Kollywood");
		al.add("Tollywood");
		al.add("Mollywood");
		al.add("Sandalwood");

		// creating String Arrays using ArrayList size
		// conversion of ArrayList to String[] Arrays
		String[] industry = al.toArray(new String[al.size()]);

		System.out.println("Conversion of "
				+ "ArrayList<String> to String[] Arrays\n");

		// print Arrays values
		for(String str : industry){
			System.out.println(str);}	
	}
}

Output:

Conversion of ArrayList<String> to String[] Arrays

Hollywood
Bollywood
Kollywood
Tollywood
Mollywood
Sandalwood

 

2. Conversion of List into Arrays using traditional way

Steps :

  • Initialize ArrayList with sample values
  • create empty String[] Arrays of ArrayList size using size(); method of ArrayList
  • Iterate through original ArrayList using traditional for-loop and assign each value of ArrayList to String[] Arrays
  • Finally, print converted String[] Arrays to console using enhanced for-each loop

ConvertListIntoArrays.java

package in.bench.resources.collection;

import java.util.ArrayList;

public class ConvertListIntoArrays {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> al = new ArrayList<String>();

		// adding elements to ArrayList object
		al.add("Hollywood");
		al.add("Bollywood");
		al.add("Kollywood");
		al.add("Tollywood");
		al.add("Mollywood");
		al.add("Sandalwood");

		// create empty String[] Arrays of ArrayList size
		String[] industry = new String[al.size()];

		// conversion of ArrayList to String[] Arrays
		// using traditional for-loop
		for(int index=0; index<industry.length; index++){

			// assign each element of AL to String[]
			industry[index] = al.get(index);
		}

		System.out.println("Conversion of "
				+ "ArrayList<String> to String[] Arrays\n");

		// print Arrays values
		for(String str : industry){
			System.out.println(str);}	
	}
}

Output:

Conversion of ArrayList<String> to String[] Arrays

Hollywood
Bollywood
Kollywood
Tollywood
Mollywood
Sandalwood

 

References:

 

Happy Coding !!
Happy Learning !!

How to sort LinkedHashMap by its Values ?