Convert array to ArrayList java

In this article, we are converting an array to ArrayList in Java. We will discuss three different ways to do that. So, I will show how to convert an Array to ArrayList in java. Get started…

Method 1: Using loops

Let’s consider the example:

package com.example.arrays;

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args){

        // creating an names array
        String[] names = {"name1","name2","name3","name4","name5","name6"};

        // creating an empty arrayList
        ArrayList<String> nameArrayList = new ArrayList<>();

        // adding array elements to the nameArrayList
        for (int i=0; i<names.length;i++){
            nameArrayList.add(names[i]);
        }

        // printing nameArrayList using for loop
        for (int j=0; j<nameArrayList.size();j++){
            System.out.println(nameArrayList.get(j));
        }

        // printing nameArrayList using forEach loop
        nameArrayList.forEach(name -> System.out.println(name));


    }
}

Firstly we created a names string array with some of the string names and an empty ArrayList. After that, we used regularly a loop for inserting names to the same ArrayList respectively.

Method 2: Using Arrays.asList()

Let’s consider another example, we convert the array to ArrayList java

package com.example.arrays;

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample2 {

    public static void main(String[] args){

        // creating an names array
        String[] names = {"name1","name2","name3","name4","name5","name6"};

        // creating an arrayList added the names array
        ArrayList<String> nameArrayList = new ArrayList<>(Arrays.asList(names));
        

        // printing nameArrayList using forEach loop
        nameArrayList.forEach(name -> System.out.println(name));

    }
}

In this example, we use Arrays.asList() method to convert arrays to the ArrayList.

I Hope, you got it.