Introduction
Converting a list to an array is a common task in Java, especially when you need to interact with APIs that require arrays or perform operations where arrays are more suitable. Java provides multiple ways to convert a list to an array, and with the introduction of Streams in Java 8, this task has become even more straightforward. In this guide, we’ll explore how to convert a list to an array using Java 8 Streams, covering both primitive and object arrays.
Problem Statement
The task is to create a Java program that:
- Accepts a list of elements.
- Converts the list to an array.
- Outputs the resulting array.
Example 1:
- Input: List of integers
[1, 2, 3, 4, 5] - Output: Array
[1, 2, 3, 4, 5]
Example 2:
- Input: List of strings
["apple", "banana", "orange"] - Output: Array
["apple", "banana", "orange"]
Solution Steps
- Input List: Start with a list of elements that can either be hardcoded or provided by the user.
- Convert List to Array Using Streams: Use the
toArray()method to convert the list into an array. - Display the Result: Print the array.
Java Program
Convert List of Integers to Array Using Streams
import java.util.Arrays;
import java.util.List;
/**
* Java 8: Convert List of Integers to Array Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class ConvertListToArrayIntegers {
public static void main(String[] args) {
// Step 1: Take input list
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Step 2: Convert the list to an array using streams
Integer[] numberArray = numbers.stream()
.toArray(Integer[]::new);
// Step 3: Display the result
System.out.println("Array: " + Arrays.toString(numberArray));
}
}
Output
Array: [1, 2, 3, 4, 5]
Explanation
In this example, the stream() method is used to create a stream from the list of integers. The toArray(Integer[]::new) method then converts the stream into an array of Integer objects. The resulting array is printed using Arrays.toString() to display the elements in a readable format.
Convert List of Strings to Array Using Streams
import java.util.Arrays;
import java.util.List;
/**
* Java 8: Convert List of Strings to Array Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class ConvertListToArrayStrings {
public static void main(String[] args) {
// Step 1: Take input list
List<String> fruits = Arrays.asList("apple", "banana", "orange");
// Step 2: Convert the list to an array using streams
String[] fruitArray = fruits.stream()
.toArray(String[]::new);
// Step 3: Display the result
System.out.println("Array: " + Arrays.toString(fruitArray));
}
}
Output
Array: [apple, banana, orange]
Explanation
This example converts a list of strings into an array using the same method as the previous example. The toArray(String[]::new) method converts the stream into an array of String objects. The resulting array is then printed out.
Convert List of Custom Objects to Array Using Streams
import java.util.Arrays;
import java.util.List;
/**
* Java 8: Convert List of Custom Objects to Array Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class ConvertListToArrayCustomObjects {
public static void main(String[] args) {
// Step 1: Take input list of custom objects
List<Student> students = Arrays.asList(
new Student("Raj", 25),
new Student("Anita", 30),
new Student("Vikram", 22)
);
// Step 2: Convert the list to an array using streams
Student[] studentArray = students.stream()
.toArray(Student[]::new);
// Step 3: Display the result
Arrays.stream(studentArray)
.forEach(student ->
System.out.println(student.getName() + ": " + student.getAge())
);
}
}
// Custom class Student
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Output
Raj: 25
Anita: 30
Vikram: 22
Explanation
In this example, a list of Student objects is converted into an array. The toArray(Student[]::new) method is used to create an array of Student objects from the stream. The array is then printed out by iterating over each element, displaying the name and age properties of each Student.
Advanced Considerations
-
Handling Primitive Types: If you’re working with lists of primitive types (e.g.,
int,double), thetoArray()method can only create arrays of their wrapper classes (Integer,Double, etc.). To convert a list of primitive values directly into a primitive array, you would typically use traditional loops or specific utility methods provided by theCollectorsclass or third-party libraries. -
Performance Considerations: Converting a list to an array using Streams is efficient for typical list sizes. However, if performance is critical and the list is very large, consider using
parallelStream()to take advantage of multi-core processors. -
Null Handling: If the list contains null values, they will be included in the array. If you need to filter out null values, you can use the
filter()method before converting the list to an array:String[] array = list.stream() .filter(Objects::nonNull) .toArray(String[]::new);
Conclusion
This guide provides methods for converting a list to an array using Java 8 Streams, covering basic scenarios like converting lists of integers, strings, and custom objects. Java 8 Streams offer a powerful and concise way to perform this conversion, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the techniques demonstrated in this guide to achieve the desired result.