Many times we need to create an ArrayList
from arrays of objects in java. There are several ways to do this using core Java APIs or third-party open-source libs like guava.
The easiest way to do this is by using the JDK Arrays class.
Using JDK to convert array to ArrayList
String[] strings = {new String("i"), new String("am"), new String("bad")};
List<String> stringList = Arrays.asList(strings);
But the above one has a fixed size so you are not able to add/remove elements. You will need to wrap it in a new ArrayList
as given below. Otherwise, you’ll get an UnsupportedOperationException.
The list returned from asList() is backed by the original array, men’s ArrayList will be using the original array object only. If you modify the original array, the list will be modified as well. This may be surprising. So change it as given below
String[] strings = {new String("i"), new String("am"), new String("bad")};
List<String> stringList = new ArrayList<>( Arrays.asList(strings));
Java 9 introduces List.of static factory method to create immutable list like Arrays.asList.
List<String> imLst = List.of(strings);
// Wrap to make new immutable array list
List<String> stringList = new ArrayList<>(imLst);
Guava Lists and ImmutableList for an array to ArrayList
Guava provides many libs for Java, which has a clutter-free simple interface to write simple, readable, and reliable code.
Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It is widely used on most Java projects within Google, and widely used by many other companies as well.
Using Guava collection lib you can create two types of List
Immutable List example
In the below example, you can create an immutable List using variable argument and array object.
List<String> il = ImmutableList.of("strings1", "strings2");
String[] strings = {new String("i"), new String("am"), new String("bad")};
List<String> il1 = ImmutableList.copyOf(strings);
Mutable List example
Using Lists class of Guava collection lib.
String[] strings = {new String("i"), new String("am"), new String("bad")};
List<String> il1 = ImmutableList.copyOf(strings);
// Create using existing list
List<String> l1 = Lists.newArrayList(il1);
// Create using array
List<String> l2 = Lists.newArrayList(strings);
// Create using var args
List<String> l3 = Lists.newArrayList("or", "string", "elements");