Convert array to arrayList java

In this article, we are converting array to arrayList in Java. We will discuss three different ways to do that. So, I am going to show how to convert 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 string names and also create an empty arrayList. After that we used regular for loop for inserting name to the nameArrayList respectively.

Method 2: Using Arrays.asList()

Let’s consider another example, we convert 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.

Hope, you got it.