Convert an Array to Mutable, Immutable and Unmodifiable Lists

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 Unmodiable List

If you want to create an unmodifiable List instance backed by array elements, follow the method below. We cannot add or remove new objects in an unmodifiable List, but we can modify the objects stored in it using the object references.

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());

2. Convert Array to Immutable List

An immutable list does not permit to add, remove or modify the items stored in it.

If you have guava library in the project then you can also use the ImmutableList.copyOf() method to get immutable list out of an array.

List<String> namesList = ImmutableList.copyOf( namesArray ); 

3. Convert Array to Mutable List

If you want to create an mutable list instance backed by array elements, follow the method below. We can add and remove new items in a mutable list and modify the existing items, too.

3.1. Using Arrays.asList()

Use Arrays.asList() to get a mutable list from an array of elements.

List<String> namesList  = Arrays.asList(namesArray);

3.2. Using Guava’s Lists.newArrayList()

Again, if you have guava library in the project, you can also use this method to get a mutable arraylist from the array.

ArrayList<String> namesList = Lists.newArrayList(namesArray);

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.