How to convert list to array in java with examples

In this tutorial you will learn how to convert list to array in java. There are so many technique and methods are available, from which you are going to learn three way for list to array conversion.

  • using list.toArray()

The best, simple and easiest way for converting list to array is by using .toArray() method. This is built-in method in java. I will highly recommend you, to used this method for purpose of list to array conversion.

Example: List to Array String Conversion.

// program to convert a List to an array in java

import java.util.*;

public class ListToArray {
	public static void main(String[] args)
	{
		List<String> list = new LinkedList<String>();
		list.add("Java");
		list.add("Tutorial");
		list.add("By");
		list.add("Programiz");

		String[] arr = list.toArray(new String[0]);

		for (String l : arr)
			System.out.print(l + " ");
	}
}

Output:

Java Tutorial By Programiz

Examples 2: List to array integer conversion

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

public class IntegerListToArray {
    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<Integer>();
        myList.add(1);
        myList.add(2);
        myList.add(3);

        Integer[] intArray = new Integer[myList.size()];
        intArray = intList.toArray(intArray);

        for(Integer i : intArray)
            System.out.println(i);
    }
}

  • Using get() method

The another way of converting list to array is by using get() method in java. See the below code of get() method implementation in java.

Examples:

// program to convert a List to an array in java

import java.io.*;
import java.util.List;
import java.util.LinkedList;

class ListToArrayGet
{
	public static void main (String[] args)
	{
		List<String> list = new LinkedList<String>();
		list.add("Java");
		list.add("Tutorial");
		list.add("By");
		list.add("Programiz");

		String[] arr = new String[list.size()];

		for (int i =0; i < list.size(); i++)
			arr[i] = list.get(i);

		for (String l : arr)
			System.out.print(l + " ");
	}
}

Output:

Java Tutorial By Programiz

  • Using stream() method

The last method of converting list to array is by using stream() method. See the below examples of list to array conversion in java.

Examples:

import java.util.*;

class ListToArrayStream {
	public static void main(String[] args)
	{
		List<String> list = new LinkedList<String>();
		list.add("Java");
		list.add("Tutorial");
		list.add("By");
		list.add("Programiz");

		int n = list.size();
		String[] arr = list.stream().toArray(String[] ::new);
		for (String x : arr)
			System.out.print(x + " ");
	}
}

Output:

Java Tutorial By Programiz

Summary

By using .toArray() built-in methods, you can easily convert list to array in java.

Was this article helpful?
YesNo

1 thought on “How to convert list to array in java with examples”

  1. Pingback: Buy Backlinks

Leave a Comment