Convert an Array to List in Java
Suppose you have an array of integer like this:
String[] myArray = {"how", "are", "you", "today"};
For whatever reason, you want to convert this array to an ArrayList
instance. There are some ways to do it.
Using Arrays.asList(T…a)
This is the easiest and simplest way to make the job done. Simply call static method asList
from java.util.Arrays
. This method returns a fixed-size list backed by the specified array.
List<String> myFixedSizeList = Arrays.asList(myArray);
However, this way has some disadvantages. The converted list is fixed size, and you can not add or remove element(s) from/to that list. If you try to do so, java.lang.UnsupportedOperationException
will be thown. Another disadvantage is the list returned from asList() is backed by the original array. That means, when you modify, for example, change the value of myArray
at index 0 to another value, the converted list will be changed as well. This my lead to unexpected behaviors that you don’t want to.
To solve those issues, you should call an constructor of java.uril.ArrayList
List<String> myDynamicList = new ArrayList<>(Arrays.asList(myArray));
Using Stream API from Java 8 and later
In Java 8, it’s easy to convert an array to list.
List<String> myList2 = Arrays.stream(myArray).collect(Collectors.toList());
or
List<String> myList3 = Stream.of(myArray).collect(Collectors.toList());
Using Guava
Guava is a set of core libraries that includes new collection types. You can convert array to list using one of these below ways:
List<String> myList4 = ImmutableList.copyOf(myArray); // This creates an immutable list
List<String> myList5 = Lists.newArrayList(myArray); // This creates an mutable list
Sample code
Sameple Java code what contains all methods above:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class Array2List {
public static void main(String... args) {
String[] myArray = {"how", "are", "you", "today"};
List<String> myFixedSizeList = Arrays.asList(myArray);
List<String> myDynamicList = new ArrayList<>(Arrays.asList(myArray));
List<String> myList2 = Arrays.stream(myArray).collect(Collectors.toList());
List<String> myList3 = Stream.of(myArray).collect(Collectors.toList());
// Lists from Guava library
List<String> myList4 = ImmutableList.copyOf(myArray); // This creates an immutable list
List<String> myList5 = Lists.newArrayList(myArray); // This creates an mutable list
}
}