
There are multiple ways in which one can initialize an ArrayList in Java with values, just like Arrays, let us take a look at a few of them.
Using an Arrays.asList()
If you already have an array that is declared and initialized, you can create Initialize an ArrayList using it.
String[] countriesArray = {"USA","China","Canada","Japan","Australia"};
List<String> arrayList = new ArrayList<>(Arrays.asList(countriesArray));
You can do this in one step as well,
List<String> arrayList = new ArrayList&ly;>(Arrays.asList("USA","China","Canada","Japan","Australia"));
Java 8: Using the Stream.of(T values) method:
ArrayList<String> arrayList = new ArrayList<>(
Stream.of("Australia", "India", "Sweden").collect(Collectors.toList())
);
Java 9: Using the List.of(Element elements) method.
ArrayList<String> arrayList = new ArrayList<>(List.of("Apple", "Banana", "Orange"));
Java 10: Using the List.copyOf() method.
ArrayList countriesList = new ArrayList<>(Arrays.asList("Canada", "UK", "France"));
ArrayList newList = new ArrayList<>(List.copyOf(countriesList));
Using Java clone() method
ArrayList<String> cityList = new ArrayList<>(Arrays.asList("NYC", "Austin", "Chicago"));
ArrayList<String> cityListClone = (ArrayList<String>) cityList.clone();
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!