How to convert list to array In Java

In Java, a list is a collection of elements that can dynamically grow and shrink in size. An array, on the other hand, is a fixed-size data structure that can store a sequence of elements of the same type. Sometimes it may be necessary to convert a list to an array in Java, for example, when we need to pass the elements of a list to a method that expects an array as an argument.

In this article, we will discuss the different ways to convert a list to an array in Java. We will explore the built-in methods provided by the Java Collections `framework`, as well as some `third-party libraries` that can simplify the conversion process.

By the end of this article, you will have a solid understanding of how to convert a list to an array in Java and will be able to apply this knowledge in your own Java programs.

Why Is There A Need To Convert List To Array In Java

In Java, a list is a dynamic data structure that can grow or shrink in size as needed, while an array is a fixed-size data structure that can store a sequence of elements of the same type. There are several reasons why you might need to convert a list to an array in Java:

1. Method arguments: Some methods in Java require an array as an argument. If you have a list of elements and need to pass them to a method that expects an array, you will need to convert the list to an array.

2.  Performance: Arrays are generally faster than lists for random access and iterating through the elements. If you need to perform operations that require quick access to elements or iterating through the elements, it might be more efficient to convert the list to an array.

3.  API compatibility: Some APIs may require you to use arrays instead of lists. In such cases, you will need to convert the list to an array to be able to use the API.

Four Methods For Converting List To Array In Java.

1. Using the to Array() method.

2. Using the toArray(T[] a) method

3. Using the Stream API.

4. Using third-party libraries.

Approach in Details

Approach 1 –  By Using the to Array() method.

The Java Collections framework provides a built-in method called toArray() that can be used to convert a list to an array. This method returns an array containing all of the elements in the list in the same order.

Sample Code:

import java.util.ArrayList;
import java.util.List;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	// Create a list of strings
    	List<String> list = new ArrayList<>();
    	list.add("apple");
        list.add("banana");
    	list.add("orange");
    	
    	// Convert the list to an array
    	String[] array = list.toArray(new String[0]);
    	
    	// Print the array
    	for (String s : array) {
        	System.out.println(s);
    	}
	}
}

Output:

apple
banana
orange

Explanation:

1. Start by creating a list of strings that contains three elements: “apple”, “banana”, and “orange”.

2. Then use the `toArray()` method to convert the list to an array.

3. Pass a new `String` array of size 0 as an argument to the `toArray()` method, which tells it to create a new array of the same type as the list.

4. Finally, iterate through the array using a for-each loop and print out each element using the `System.out.println()` method.

5. Overall, the `toArray()` method is a simple and efficient way to convert a list to an array in Java. It is important to ensure that the type of the array that you are creating matches the type of the elements in the list to avoid runtime errors.

Approach 2 – By Using the toArray(T[] a) method

This method is similar to the `toArray()` method, but it allows you to specify the type of the array that you want to create. This can be useful if you need to create an array of a specific type. The `toArray(T[] a)` method takes an array of type `T[]` as an argument and returns an array of type `T[]` containing the elements of the list. If the size of the provided array is greater than or equal to the size of the list, then the method fills the provided array with the elements of the list and returns it. Otherwise, the method creates a new array of the same type as the provided array and fills it with the elements of the list.

Sample Code:

import java.util.ArrayList;
import java.util.List;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	// Create a list of doubles
    	List<Double> list = new ArrayList<>();
    	list.add(1.1);
    	list.add(2.2);
    	list.add(3.3);
 
    	// Create an array of doubles with the same size as the list
    	Double[] array = new Double[list.size()];
 
    	// Convert the list to the array using the toArray(T[] a) method
    	array = list.toArray(array);
 
    	// Print the array
    	for (Double d : array) {
        	System.out.println(d);
    	}
	}
}

Output:

1.1
2.2
3.3

Explanation:

1. Start by creating a List of doubles that contains three elements: 1.1, 2.2, and 3.3.

2. Then create an array of doubles with the same size as the list using the `list.size()` method.

3. Then use the `toArray(T[] a)` method to convert the list to the array.

4. Pass the array variable as an argument to the method to tell it to use this array instead of creating a new one.

5. Finally, iterate through the array using a for-each loop and print out each element using the `System.out.println()` method.

Approach – 3 – By Using the Stream API

The Java 8 Stream API provides a convenient way to convert a list to an array. You can use the `stream()` method to convert the list to a stream and then use the `toArray()` method to convert the stream to an array. Additionally, it provides a concise and elegant way to convert a List to an array.

Sample Code:

import java.util.ArrayList;
import java.util.List;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	// Create a list of integers
    	List<Integer> list = new ArrayList<>();
    	list.add(1);
    	list.add(2);
    	list.add(3);
    	list.add(4);
    	list.add(5);
 
    	// Convert the list to an array using the Stream API
    	Integer[] array = list.stream()
            	.filter(n -> n % 2 == 0) // filter out odd numbers
            	.toArray(Integer[]::new);
 
    	// Print the elements of the array
    	for (Integer i : array) {
        	System.out.println(i);
    	}
	}
}

Output:

2
4

Explanation:

1. Create a List of integers that contains five elements.

2. Then use the `stream()` method of the List interface to create a stream of elements from the list, and call the `filter()` method on the stream to filter out odd numbers.

3. Pass a lambda expression to the `filter()` method that checks whether each element of the stream is even by using the modulo operator (%).

4. If an element is even, it is included in the stream, otherwise it is filtered out.

5. Finally, call the `toArray()` method on the stream to create an array of integers, and pass a method reference Integer[]::new to the `toArray()` method to create a new array of integers with the appropriate size based on the size of the stream.

6. Iterate through the array using a for-each loop and print out each element of the array using the `println()` method.

 Approach – 4 – By Using Third-Party Libraries

There are several third-party libraries, such as Apache Commons Lang and Google Guava, that provide utility methods for converting lists to arrays. These libraries can simplify the conversion process and provide additional functionality. One of the most popular libraries is Apache Commons Lang.

Sample Code:

import org.apache.commons.lang3.ArrayUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	List<Integer> integerList = new ArrayList<>();
    	Random random = new Random();
    	
    	// populate the list with random integers
    	for (int i = 0; i < 10; i++) {
            integerList.add(random.nextInt(100));
    	}
 
    	// convert the list to an array
    	Integer[] integerArray = ArrayUtils.toArray(integerList, Integer.class);
 
    	// print the original list and the array
    	System.out.println("Original List: " + integerList);
    	System.out.println("Array: " + ArrayUtils.toString(integerArray));
	}
}

Output:

Original List: [36, 87, 33, 96, 51, 23, 27, 56, 60, 47]
Array: [36, 87, 33, 96, 51, 23, 27, 56, 60, 47]

Explanation:

1. First create an empty `ArrayList` of Integer objects.

2. Then use a for loop to populate the list with 10 random integers generated using the `nextInt()` method of the Random class.

3. Pass the list and the class of the array that we want to create (Integer.class) to the ArrayUtils.toArray() method.

4. This method returns an array of the specified class that contains the elements of the input list.

5. Finally, use the `toString()` method from the `ArrayUtils` class to print the original list and the array.

6. Note that we need to import the `ArrayUtils` class from the org.apache.commons.lang3 package to use the `toArray()` method.

7. Also, we need to pass the class of the array that we want to create as the second argument to the `toArray()` method.

Best Approach For Converting The List To Array In Java:

 The best approach for converting a list to an array in Java is to use the `toArray(T[] a)` method with a pre-allocated array.

1. Type safety: Using the `toArray(T[] a)` method with a pre-allocated array ensures that the resulting array has the correct type, which provides an additional level of type safety.

2. Performance: Using the `toArray(T[] a)` method with a pre-allocated array is generally faster than using a stream or a third-party library, as it avoids the overhead of creating a new array object.

3. Flexibility: The `toArray(T[] a)` method allows you to control the size and type of the resulting array, which provides greater flexibility and customization options.

4. In some cases, the `toArray(T[] a)` method provides the best balance of type safety, performance, and flexibility.

 Sample problem for converting list to array In Java.

Sample problem 1.

Problem:

You are given a list of integers, and you need to convert it to an array and find the sum of all the even integers in the array.

Solution:

The output will show the `toArray()` method has successfully converted the list to an array, and  successfully calculated the sum of all even integers in the array (which is 2 + 4 = 6). Finally, this example has demonstrated how to use the `toArray()` method to convert a list to an array and perform simple operations on the resulting array.

Code:

import java.util.ArrayList;
import java.util.List;
 
public class ListToArraySumExample {
	public static void main(String[] args) {
    	// Create a list of integers
    	List<Integer> list = new ArrayList<>();
    	list.add(1);
    	list.add(2);
    	list.add(3);
    	list.add(4);
    	list.add(5);
    	
    	// Convert the list to an array
    	Integer[] array = list.toArray(new Integer[0]);
    	
    	// Calculate the sum of even integers in the array
    	int sum = 0;
    	for (int i : array) {
        	if (i % 2 == 0) {
            	sum += i;
        	}
    	}
       
    	// Print the sum
    	System.out.println("Sum of even integers in the array: " + sum);
	}
}

Output:

Sum of even integers in the array: 6

Explanation:

1.  Start by creating a list of integers that contains five elements: 1, 2, 3, 4, and 5.

2.  Then use the `toArray()` method to convert the list to an array of type `Integer`.

3.  Then iterate through the array using a for-each loop and check if each element is even by using the modulus operator `(%)`.

4.  If an element is even, add it to the sum variable.

5.  Finally, print the value of sum by using the System.out.println() method.

Sample Problem 2:

Problem:

Write a Java program that takes a `List` of `Person` objects and converts it to an array of Person objects using the `toArray(T[] a)` method. The program should then print out the name of each person in the resulting array.

Solution:

The output will show  the `toArray(T[] a)` method has successfully converted the list of Person objects to an array of Person objects, and the array contains all of the objects in the list in the same order.

Code:

import java.util.ArrayList;
import java.util.List;
 
class Person {
	private String name;
	private int age;
 
	public Person(String name, int age) {
    	this.name = name;
    	this.age = age;
	}
 
	public String getName() {
    	return name;
	}
}
 
public class ListToObjectArrayExample {
	public static void main(String[] args) {
    	// Create a list of Person objects
    	List<Person> list = new ArrayList<>();
    	list.add(new Person("Alice", 25));
    	list.add(new Person("Bob", 30));
    	list.add(new Person("Charlie", 35));
 
    	// Create an array of Person objects with the same size as the list
    	Person[] array = new Person[list.size()];
 
    	// Convert the list to the array using the toArray(T[] a) method
    	array = list.toArray(array);
 
    	// Print the names of each person in the array
    	for (Person p : array) {
        	System.out.println(p.getName());
    	}
	}
}

Output:

Alice
Bob
Charlie

Explanation:

1. In this program, start by creating a List of Person objects that contains three elements.

2. Each Person object has a name and an age.

3. Then create an array of Person objects with the same size as the list using the `list.size()` method.

4. Then use the `toArray(T[] a)` method to convert the list to the array.

5. Pass the array variable as an argument to the method to tell it to use this array instead of creating a new one.

6. Finally, iterate through the array using a for-each loop and print out the name of each person using the `getName()` method.

Sample Problem 3:

Problem:

Write a Java program that creates a list of Employee objects, filters out the employees who have a salary less than or equal to 50000, and converts the resulting list of Employee objects to an array using the `Stream API`.

Solution:

Assume that the Employee class has the following properties: id (int), name (String), salary (double).

Code:

import java.util.ArrayList;
import java.util.List;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	// Create a list of Employee objects
    	List<Employee> employeeList = new ArrayList<>();
    	employeeList.add(new Employee(1, "John", 40000.0));
    	employeeList.add(new Employee(2, "Mary", 55000.0));
    	employeeList.add(new Employee(3, "Bob", 60000.0));
    	employeeList.add(new Employee(4, "Alice", 45000.0));
    	employeeList.add(new Employee(5, "David", 75000.0));
 
    	// Use the Stream API to filter out employees with salary less than or equal to 50000 and convert to array
    	Employee[] employeesArray = employeeList.stream()
            	.filter(e -> e.getSalary() > 50000.0) // filter out employees with salary less than or equal to 50000
            	.toArray(Employee[]::new); // convert the remaining employees to an array
 
    	// Print the employees in the array
    	System.out.println("Employees with salary greater than 50000 in the array: ");
    	for (Employee e : employeesArray) {
        	System.out.println(e);
    	}
	}
}
 
class Employee {
	private int id;
	private String name;
	private double salary;
 
	public Employee(int id, String name, double salary) {
    	this.id = id;
    	this.name = name;
    	this.salary = salary;
	}
 
	public int getId() {
    	return id;
	}
 
	public String getName() {
    	return name;
	}
 
	public double getSalary() {
    	return salary;
	}
 
	@Override
	public String toString() {
    	return "Employee{" +
            	"id=" + id +
            	", name='" + name + '\'' +
            	", salary=" + salary +
            	'}';
	}
}

Output:

Employees with salary greater than 50000 in the array:
Employee{id=2, name='Mary', salary=55000.0}
Employee{id=3, name='Bob', salary=60000.0}
Employee{id=5, name='David', salary=75000.0}

Explanation:

1. Create a List of Employee objects that contains five elements.

2. Then use the `stream()` method of the List interface to create a stream of elements from the list, and call the `filter()` method on the stream to filter out employees who have a salary less than or equal to 50000.

3. Finally, call the `toArray()` method on the stream to create an array of Employee objects, and pass a method reference Employee[]::new to the `toArray()` method to create a new array of the same type.

4. Then print the employees in the array using a for-each loop and the `toString()` method of the Employee class.

Sample Problem 4:

Problem:

Given two arrays of integers, combine them into a single array and print the result.

Solution:

We need to import the `ArrayUtils` class from the `org.apache.commons.lang3` package to use the `toArray()` method. Also, notice that the resulting array has the type `Integer[]`, not `int[]`. If you need an `int[]` array instead, you can use the `Arrays.stream()` method and the `toArray()` method with an `IntFunction` argument.

Code:

import org.apache.commons.lang3.ArrayUtils;
 
import java.util.Arrays;
import java.util.List;
 
public class ListToArrayExample {
	public static void main(String[] args) {
    	List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
 
    	// convert list to array
    	Integer[] integerArray = ArrayUtils.toArray(integerList);
 
    	// print the result
    	System.out.println("Result array: ");
    	for (int i : integerArray) {
        	System.out.print(i + " ");
    	}
	}
}

Output:

Result array:
1 2 3 4 5

Explanation:

1. In this example, start by creating a list of integers `integerList` using the `Arrays.asList()` method.

2. Then pass this list to the `ArrayUtils.toArray()` method to convert it to an array of Integer objects.

3. Finally, use a for loop to print the elements of the resulting array .

Conclusion:

In conclusion, converting a list to an array in Java can be done using various methods, including the `toArray()` method, the `toArray(T[] a)` method, the `stream API`, and `third-party libraries`. Each method has its own advantages and disadvantages in terms of type safety, performance, and flexibility.

After considering these factors, the best approach for converting a list to an array in Java is to use the `toArray(T[] a)` method with a pre-allocated array. This approach provides type safety, better performance, and greater flexibility.

However, the choice of method ultimately depends on the specific requirements of the use case.