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,

 

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete