Convert array to list in Java

Learn different and useful ways to convert array to list in Java. In this example, we will use Java 8 classes and Google guava library for creating an arraylist from elements of given array.

1. Convert array to list – Immutable arraylist

If you want to create an immutable arraylist instance backed by array elements then follow any given method below.

1.1. Collections.unmodifiableList()

Use Collections.unmodifiableList() to get a immutable list

String[] namesArray = new String[] {"alex", "brian", "charles", "david"};
        
List<String> namesList = Collections.unmodifiableList( Arrays.asList(namesArray) ); 

System.out.println(namesList);

Program output.

[alex, brian, charles, david]

1.2. ImmutableList.copyOf()

If you have guava library in project then you can use this method as well to get immutable list out of string array.

String[] namesArray = new String[] {"alex", "brian", "charles", "david"};
        
List<String> namesList = ImmutableList.copyOf( namesArray ); 

System.out.println(namesList);

Program output.

[alex, brian, charles, david]

2. Convert array to list – Mutable arraylist

If you want to create an mutable list instance backed by array elements then follow any given method below.

2.1. Arrays.asList()

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

String[] namesArray = new String[] {"alex", "brian", "charles", "david"};
        
List<String> namesList  = Arrays.asList(namesArray) ; 

System.out.println(namesList);

Program output.

[alex, brian, charles, david]

2.2. Lists.newArrayList()

Again, if you have guava library in project then you can use this method as well to get mutable arraylist from array.

String[] namesArray = new String[] {"alex", "brian", "charles", "david"};
        
ArrayList<String> namesList = Lists.newArrayList(namesArray);

System.out.println(namesList);

Program output.

[alex, brian, charles, david]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs
Arrays Java Docs
Google Guava Docs

Leave a Reply

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.

Our Blogs

REST API Tutorial