How to Initialize ArrayList Java with Values


Initialize ArrayList in Java Example

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();

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap