Learn different and useful ways to convert an array into a List in Java. In this example, we will use Java 8 classes and Google guava library to create an ArrayList from the given array’s elements.
1. Convert Array to Immutable List
If you want to create an immutable List instance backed by array elements, follow any given method below.
1.1. Using List.of() – Java 9
Since Java 9, we can use List.of() methods that return an unmodifiable list containing the array elements.
List<String> namesList = List.of(namesArray);
1.2. Using Collections.unmodifiableList() – Java 8
Till Java 8, use Collections.unmodifiableList()
to get an unmodifiable list containing the array elements.
String[] namesArray = new String[] {"alex", "brian", "charles", "david"};
List<String> namesList = Collections.unmodifiableList( Arrays.asList(namesArray) );
1.3. Using Java 8 Streams
The Steam API is also an excellent option for collecting the array of elements into List. Streams allow us the option to filter and perform the intermediate operations as well.
List<String> namesList = Arrays.stream(namesArray).collect(Collectors.toUnmodifiableList());
1.4. Using Guava’s ImmutableList.copyOf()
If you have guava library in project then you can also use this method to get immutable list out of string array.
List<String> namesList = ImmutableList.copyOf( namesArray );
2. Convert Array to Mutable List
If you want to create an mutable list instance backed by array elements, follow any given method below.
2.1. Using Arrays.asList()
Use Arrays.asList()
to get a mutable list from a array of elements.
List<String> namesList = Arrays.asList(namesArray);
2.2. Using Guava’s Lists.newArrayList()
Again, if you have guava library in project then you can also use this method to get a mutable arraylist from array.
ArrayList<String> namesList = Lists.newArrayList(namesArray);
Happy Learning !!
Leave a Reply