Learn how to convert array to list and list to array in Java with examples. Discover modifiability constraints and best practices.
1. Introduction
Converting between arrays and lists is a common task in Java programming. Knowing these conversions is essential whether you’re handling legacy code or leveraging modern Java features. In this guide, we’ll explore various ways to convert arrays to lists and lists to arrays in Java using plain Java, libraries, and Java 8+ features.
2. Converting Array to List
2.1. Using Plain Java – Arrays.asList
The simplest way to convert an array to a list in Java is by using the Arrays.asList
method. This method takes an array as an argument and returns a fixed-size list backed by the specified array. This means that any changes made to the array will reflect in the list and vice versa.
Code Example:
import java.util.Arrays;
import java.util.List;
public class ArrayToListExample {
public static void main(String[] args) {
String[] array = {"Java", "Python", "C++"};
System.out.println("Array: " + Arrays.toString(array));
List<String> list = Arrays.asList(array);
System.out.println("List: " + list);
}
}
ArrayToListExample.javaOutput:
Array: [Java, Python, C++]
List: [Java, Python, C++]
CMDThings to consider:
- Fixed-Size List:
- The list returned by Arrays.asList is backed by the original array.
- This means the size of the list cannot be changed (i.e., you cannot add or remove elements).
- Attempting to modify the size, such as list.add(“C#”) or list.remove(“Python”), will throw an UnsupportedOperationException.
- Modifiable Elements
- While the size is fixed, you can modify the elements of the list. Changes to the list will reflect in the original array and vice versa because the list is just a view of the array.
- Sequence of Elements
- The sequence of elements in the list is guaranteed to match the sequence in the original array.
2.2. Using Plain Java – Using ArrayList Constructor
By wrapping the Arrays.asList result in an ArrayList, you can create a fully modifiable list. This approach allows resizing the list by adding or removing elements, unlike the fixed-size list from Arrays.asList.
Code Example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToListExample {
public static void main(String[] args) {
String[] array = {"Java", "Python", "C++"};
System.out.println("Array: " + Arrays.toString(array));
List<String> list = new ArrayList<>(Arrays.asList(array));
list.add("Ruby");
System.out.println("Modifiable List: " + list);
}
}
ArrayToListExample.javaOutput:
Array: [Java, Python, C++]
Modifiable List: [Java, Python, C++, Ruby]
CMDThings to consider:
- Modifiable List
- The list is completely independent of the original array.
- Changes to the list do not affect the original array, and vice versa.
- Resizable
- You can freely add or remove elements using list add and remove methods.
- Independent Copy
- This approach creates a new list that is a shallow copy of the array’s contents. The list is not backed by the array, unlike Arrays.asList.
2.3. Using Java 8 Streams
Streams provide a functional and flexible way to convert arrays into lists. This approach not only allows simple conversion but also supports transformations, such as filtering or mapping, during the process.
Code Example:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayToListExample {
public static void main(String[] args) {
String[] array = {"Java", "Python", "C++"};
System.out.println("Array: " + Arrays.toString(array));
List<String> list = Arrays.stream(array).collect(Collectors.toList());
System.out.println("List using Streams: " + list);
}
}
ArrayToListExample.javaOutput:
Array: [Java, Python, C++]
List using Streams: [Java, Python, C++]
CMDThings to consider:
- Sequence of Elements
- The resulting list maintains the same sequence of elements as the original array unless explicitly transformed during the stream operations.
- Modifiability
- The list created using Collectors.toList() is modifiable, allowing additions, removals, and modifications of elements.
- Functional Transformations
- Streams allow operations such as filtering or mapping to modify or filter elements before collecting them into a list.
2.4. Using Guava – Lists.newArrayList
The Guava library provides a convenient and straightforward way to create a modifiable ArrayList from an array. This method is simple and integrates seamlessly with the Guava ecosystem.
Code Example:
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.List;
public class ArrayToListExample {
public static void main(String[] args) {
String[] array = {"Java", "Python", "C++"};
System.out.println("Array: " + Arrays.toString(array));
List<String> list = Lists.newArrayList(array);
list.add("Ruby");
System.out.println("Guava List: " + list);
}
}
ArrayToListExample.javaOutput:
Array: [Java, Python, C++]
Guava List: [Java, Python, C++, Ruby]
CMDThings to consider:
- Sequence of Elements
- The Lists.newArrayList method retains the sequence of elements from the original array.
- Modifiability
- The list created is a standard ArrayList, fully resizable and modifiable.
Guava Dependency: To use Guava in your project, add the following dependency to your pom.xml:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.3.1-jre</version>
</dependency>
pom.xmlYou can find the latest version of Guava on Maven Central.
2.5. Using Apache Commons Collections
The Apache Commons Collections library provides a convenient and efficient way to convert an array into a modifiable list using the CollectionUtils.addAll() method. This approach simplifies the process of adding all elements from an array to a list and integrates seamlessly with the Apache Commons Collections ecosystem.
Code Example:
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToListExample {
public static void main(String[] args) {
String[] array = {"Java", "Python", "C++"};
System.out.println("Array: " + Arrays.toString(array));
List<String> list = new ArrayList<>(array.length);
CollectionUtils.addAll(list, array);
System.out.println("List: " + list);
}
}
ArrayToListExample.javaOutput:
Array: [Java, Python, C++]
List: [Java, Python, C++]
CMDThings to consider:
- CollectionUtils.addAll()
- Apache Commons Collections provides the addAll() method to efficiently add all elements from an array (or any Collection) into a list.
- The method does not require manually iterating over the array or list to add elements. It takes the List to which elements should be added and the array itself.
- Modifiability
- The resulting List is an ArrayList, so it is fully modifiable. You can add, remove, or modify elements of the list after conversion.
- The list is independent of the original array, meaning changes to the list won’t affect the array, and vice versa.
- Sequence of Elements
- The order of elements from the original array is preserved when added to the List. The CollectionUtils.addAll() method ensures that the elements are inserted in the same sequence.
Apache Commons Collections Dependency: To use Apache Commons in your project, add the following dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.5.0-M2</version>
</dependency>
pom.xmlYou can find the latest version of Apache Commons Collections on Maven Central.
3. Converting List to Array
3.1. Using Plain Java – toArray method
The toArray method provides a straightforward way to convert a List into an array in Java. It ensures that the array contains the same sequence of elements as the list.
Code Example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListToArrayExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Java", "Python", "C++"));
System.out.println("List: " +list);
String[] array = list.toArray(new String[0]);
System.out.println("Array: " + Arrays.toString(array));
}
}
ListToArrayExample.javaOutput:
List: [Java, Python, C++]
Array: [Java, Python, C++]
CMDThings to consider:
- Generic Type Specification
- The toArray(new String[0]) ensures the resulting array has the correct type (String[] in this case).
- Modifiability
- The created array is not linked to the original list, meaning modifications to the array will not affect the list and vice versa.
- Sequence of Elements
- The resulting array preserves the same sequence of elements as the source list.
3.2. Using Java 8 Streams
Streams provide a functional and flexible approach for converting a list to an array. This method also allows for transformations, such as filtering or mapping, during the conversion process.
Code Example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListToArrayExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("Java", "Python", "C++"));
System.out.println("List: " +list);
String[] array = list.stream().toArray(String[]::new);
System.out.println("Array using Streams: " + Arrays.toString(array));
}
}
ListToArrayExample.javaOutput:
List: [Java, Python, C++]
Array using Streams: [Java, Python, C++]
CMDThings to consider:
- Custom Array Generator
- String[]::new is a method reference specifying the type of array to generate, ensuring type safety without casting.
- Modifiability
- The created array is not linked to the original list, meaning modifications to the array will not affect the list and vice versa.
- Sequence of Elements
- The stream() method processes the list sequentially, ensuring the order of elements is preserved in the resulting array.
3.3. Using Guava – toArray
The Guava library provides a convenient and efficient way to convert a List to an array using the toArray
method. This method simplifies the conversion by directly handling the transformation from a List to an array, without requiring manual iteration or additional steps. It is particularly useful when working with lists of primitive types, as it eliminates the need for autoboxing and provides a seamless experience when dealing with primitive arrays in the Guava ecosystem.
Code Example:
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import java.util.Arrays;
import java.util.List;
public class ListToArrayExample {
public static void main(String[] args) {
List<Integer> list = Lists.newArrayList(1, 3, 2, 5, 4, 7);
System.out.println("List: " + list);
int[] array = Ints.toArray(list);
System.out.println("Guava Array: " + Arrays.toString(array));
}
}
ListToArrayExample.javaOutput:
List: [1, 3, 2, 5, 4, 7]
Guava Array: [1, 3, 2, 5, 4, 7]
CMDThings to consider:
- Efficient Conversion
- Guava’s Ints.toArray() directly converts a List<Integer> into a primitive int[], avoiding unnecessary boxing and improving performance when working with primitive types.
- Modifiability
- The resulting int[] array is independent of the original list. Any modifications to the array will not affect the original list, and changes to the list will not affect the array.
- Sequence of Elements
- The Ints.toArray() method preserves the order of elements from the original List<Integer> when converting to the int[] array, ensuring the elements appear in the same sequence in the resulting array.
4. Things to Consider
Here are some important considerations to keep in mind while converting list to array and array to list:
- Modifiability of Lists: When using
Arrays.asList
, the list is backed by the original array, so its size is fixed. You can modify elements but cannot add or remove them. If you need a modifiable list, consider wrapping the result with anArrayList
. Guava’sLists.newArrayList
and Java 8 streams create fully modifiable lists that can grow and shrink as needed. - Type Safety: Always specify the correct type when converting between arrays and lists. When converting from a list to an array using
toArray(new T[0])
, make sure to use the proper type to avoidClassCastException
. - Library Dependencies: Guava introduces an external dependency to your project. If minimizing dependencies is important for your project, weigh the benefits of Guava’s cleaner syntax against its inclusion in your dependencies.
- Compatibility with Legacy Code: If you are working with legacy code that already uses older Java versions, you may not be able to use Java 8 streams. In such cases, consider using plain Java methods or Guava’s utilities for backward compatibility.
5. FAQs
Which method is best for large data?
For scalability, Java 8 streams are preferred as they efficiently handle transformations and parallel processing.
What is the difference between using Arrays.asList and ArrayList for converting an array to a list?
Arrays.asList returns a fixed-size list backed by the original array, meaning you can’t add or remove elements from the list. In contrast, using ArrayList allows you to create a resizable list by wrapping the result of Arrays.asList, making it fully modifiable.
6. Conclusion
In conclusion, converting between arrays and lists in Java is a common task that can be achieved through various methods, each with its own advantages and considerations. Whether you choose to use plain Java, Java 8 streams, or Guava, understanding the differences in modifiability, performance, and compatibility with legacy code is crucial for selecting the best approach for your needs.
7. Learn More
Interested in learning more?
Remove Null Values from List in Java
Add a Comment