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

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.