With subscript, we can instantly fetch the data elements stored in the memory. So to leverage the power of subscript, we may need to convert a list into an array.

Therefore in this programming example, we will learn to convert a Java List (or ArrayList) into an Array.

Method 1: Using Loop

The conventional method of converting a list into an array is to declare an array of the same size as the list and fill the data by iterating through the list items.

We can implement this in Java by the following steps:

  1. Declare an array of the same type and size as the List.
  2. Iterate through the list items and assign them to the array at the corresponding index.

Here is the implementation of the steps in Java:

import java.util.ArrayList;
import java.util.List;
 
public class Main{
  public static void main(String args[]){
    //Intialze list with values
    List<Integer> numbers = new ArrayList<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    
    //Declare an array of same size
    Integer array[] = new Integer[numbers.size()];

    //Iterate through list items and
    //assign them to the array
    int k=0;
    for(Integer num: numbers){
      array[k] = num;
      k++;
    }

    //Output array
    System.out.print("Array: ");
    for(int i=0; i<k; i++){
        System.out.print(array[i]+ " ");
    }
  }
}

Output:

Array: 1 2 3 4

The time complexity of this method is O(n) because we are explicitly looping through the given ‘n’ items of the list and adding them to the array.

This method works for both primitive and reference types of data.

Method 2: Using List.toArray()

According to StackOverflow, toArray() method of the List class returns an array of the items in the list.

Syntax in Java 8:

<Type>[] <array_name> = list.stream().toArray(<Type>[]::new);

Syntax in Java 11:

<Type>[] <array_name> = list.toArray(<Type>[]::new);

Here is an example in Java, in which we are converting an integer list to an integer array:

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

class Main {
  public static void main(String[] args) {
    //Initialze list with items
    List<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4); 

    //Assign returned value from list.toArray() to the array
    Integer array[] = list.toArray(Integer[]::new);
    
    //output the array
     System.out.print("Array: ");
    for(Integer in: array){
      System.out.print(in+" ");
    }
    
  }
}

Output:

Array: 1 2 3 4

This method works only with the referenced data types. If you want to use it with primitive’s data then use its wrapper class (e.g., Integer instead of int as shown in the above example).

In this tutorial, we learned how to convert a list into an array in Java programming language. Comment below if you know some other methods.

Leave a Reply