Java - Converting list to array

Posted on October 22, 2016


In Java, we can convert the List to array by using

  • Loops (for/while/do-while)
  • List.toArray()
  • Stream (Introduced in Java8)

ListToArrayExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 *
 */
public class ListToArrayExample {
	public static void main(String[] args) {
		//List to be converted into array
		List<String> list=new ArrayList<>();
		list.add("A");
		list.add("B");
		list.add("C");
		list.add("D");
		list.add("E");
		
		/*Method - 1 (Using for loop)*/
		String[] array1=new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			array1[i]=list.get(i);
		}
		System.out.println("Method -1 Output:");
		for (String string : array1) {
			System.out.println(string);
		}
		
		/*Method - 2 (List.toArray())*/
		String[] array2=list.toArray(new String[list.size()]);
		System.out.println("\nMethod -2 Output:");
		for (String string : array2) {
			System.out.println(string);
		}
		
		/*Method - 3 (Using stream)*/
		String[] array3=list.stream().toArray(String[]::new);
		System.out.println("\nMethod -3 Output:");
		for (String string : array3) {
			System.out.println(string);
		}
	}
}

Output

Method -1 Output:
A
B
C
D
E

Method -2 Output:
A
B
C
D
E

Method -3 Output:
A
B
C
D
E