Java - How to create an ArrayList from an Array?

In this section, we will show you how to create an ArrayList from an Array

Following ways can be used for converting Array to ArrayList:
  1. By using Arrays.asList() method
  2. By using Collections.addAll() method
  3. By adding each element of the Array to ArrayList explicitly

Example 1: By using Arrays.asList() method 

Using asList() method from an Arrays class will convert the given Array to an ArrayList.

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

public class Main {

public static void main(String []args)
{
String [] strArray =
{"Java", "Kotlin", "C", "Go", "Python"};
ArrayList<String> list =
new ArrayList<String>(Arrays.asList(strArray));
System.out.println(list);
}
}

Console Output:
[Java, Kotlin, C, Go, Python]


Example 2: By using Collections.addAll() method

Using addAll() method from the Collections class will convert Arrays to Arraylist. We pass two parameters to the addAll method that is ArrayList and Array.

import java.util.ArrayList;
import java.util.Collections;

public class Main {

public static void main(String []args)
{
String [] strArray =
{"Java", "Kotlin", "C", "Go", "Python"};
ArrayList<String> list= new ArrayList<String>();
Collections.addAll(list, strArray);
System.out.println(list);
}
}


Console Output:
[Java, Kotlin, C, Go, Python]


Example 3: By adding each element of the array to ArrayList explicitly

import java.util.ArrayList;

public class Main {

public static void main(String []args)
{
String [] strArray =
{"Java", "Kotlin", "C", "Go", "Python"};
ArrayList<String> list= new ArrayList<String>();
for(int i =0;i<strArray.length;i++)
{
list.add(strArray[i]);
}
System.out.println(list);
}
}

Console Output:
[Java, Kotlin, C, Go, Python]

More related topics,

 

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example