Arrays.aslist immutable

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 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 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 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 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?

Let us know if you liked the post. Thats the only way we can improve.
Yes
No

Video liên quan

Chủ Đề