How To Convert Array To Arraylist In Java

Arrays and ArrayLists are data structures used for storing collections of elements in Java. Arrays have a fixed size and lack many of the useful methods and functions found in ArrayLists, while ArrayLists are dynamic and can be expanded or contracted as needed.

To take advantage of the ArrayList’s additional features and work with a resizable data structure, it may be helpful to convert an array to an ArrayList. This can be achieved using methods such as Arrays.asList(), Collections.addAll(), or a loop to add each element of the array to the ArrayList.

The Arrays.asList() method is simple and effective but may not work as expected with arrays of primitive types. The Collections.addAll() method is also simple and efficient, and works with any type of array, but does not preserve the order of the original array. A loop to iterate over each element of the array is a simple and effective approach for smaller arrays or when order is important.

Ultimately, the choice of the best approach depends on the specific requirements of the use case. However, by converting an array to an ArrayList, we can easily take advantage of the additional features and methods offered by the ArrayList class.

Here’s an example code snippet that converts an array to an ArrayList in Java:

String[] array = {"apple", "banana", "cherry", "date"};
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));

Why do we need to convert array to arraylist in java

In Java, a number of factors make the conversion of an array to an ArrayList essential:

  1. Over time, ArrayLists grow or shrink in size: As new elements are added or removed, ArrayLists, in contrast to arrays, can dynamically expand or contract. They are more adaptable than arrays when working with data of variable or unknown size.
  2. ArrayLists have the following built-in methods: Built-in methods like sorting, searching, and adding or removing elements can be used to change the data in ArrayLists. These methods can simplify and make your code more effective.
  3. ArrayLists can handle a variety of data types, including In contrast to arrays, which can only hold elements of a single data type, ArrayLists can hold elements of multiple data types. As a result, when working with intricate data structures, they are more adaptable.
  4. Interoperability with APIs: Many Java APIs are designed to work with ArrayLists rather than arrays. Converting your data to an ArrayList rather than an array can simplify working with these APIs and their built-in methods.

Converting your code from an array to an ArrayList can improve its flexibility, efficiency, and ease of use when dealing with complex data structures or APIs designed to work with ArrayLists.

In Java, there are various ways to transform an array into an ArrayList.

Some common approaches include:

  • Using the Arrays.asList() method
  • Using Collections.addAll() method
  • Using a loop

Approach 1- Using Arrays.asList() method:

The Arrays.asList() method in Java converts an array to an ArrayList. It creates a fixed-size list backed by the specified array, meaning any changes made to the list will be reflected in the original array. This approach is useful when you need to work with an array and an ArrayList simultaneously or when you need to pass an array as a parameter to a method that expects an ArrayList..

Code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArrayToArrayListExample {
public static void main(String[] args) {
        String[] arr = {"apple", "banana", "cherry"}; 
        List<String> list = new ArrayList<>(Arrays.asList(arr)); 
        System.out.println("Original Array: " + Arrays.toString(arr));
        System.out.println("ArrayList: " + list);
        list.add("date");
        System.out.println("Modified ArrayList: " + list);
    }
}

Output:

Original Array: [apple, banana, cherry]
ArrayList: [apple, banana, cherry]
Modified ArrayList: [apple, banana, cherry, date]

Code Explanation:

  • The code imports the necessary classes from the java.util package to create an ArrayList and convert an array to an ArrayList.
  • A string array of three elements (“apple”, “banana”, “cherry”) is created and assigned to the variable arr.
  • The Arrays.asList method is called to convert the arr array to an ArrayList, and the resulting ArrayList is assigned to the variable list.
  • The original array arr and the resulting ArrayList list are printed to the console using the System.out.println method.
  • A new element “date” is added to the ArrayList using the list.add method.
  • The modified ArrayList is printed to the console using the System.out.println method.
  • The output shows the original array, the ArrayList created from it, and the modified ArrayList with the added element “date”.

Approach 2- Using Collections.addAll() method:

The Collections.addAll() method in Java adds all elements of an array to a collection in the order they are passed in. This is useful when you need to add the elements of an array to an existing collection or create a new collection with elements from one or more arrays.

Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayToArrayListExample {
    public static void main(String[] args) {
        String[] arr = {"apple", "banana", "cherry"};
        List<String> list = new ArrayList<>();
        Collections.addAll(list, arr);
        
        System.out.println("Original Array: " + String.join(", ", arr));
        System.out.println("ArrayList: " + list);
        list.add("date"); 
        System.out.println("Modified ArrayList: " + list);
    }
}

Output:

Original Array: apple, banana, cherry
ArrayList: [apple, banana, cherry]
Modified ArrayList: [apple, banana, cherry, date]

Code Explanation:

  • The code creates a string array of three elements (“apple”, “banana”, “cherry”) and assigns it to the variable arr.
  • An empty ArrayList is created and assigned to the variable list.
  • The Collections.addAll method is called to add all the elements from the arr array to the list ArrayList.
  • The original array arr and the resulting ArrayList list are printed to the console using the System.out.println method.
  • A new element “date” is added to the ArrayList using the list.add method.
  • The modified ArrayList is printed to the console using the System.out.println method.
  • The output shows the original array, the ArrayList created from it, and the modified ArrayList with the added element “date”.

Approach 3-  Using a loop:

To convert an array to an ArrayList in Java, a loop can also be used where an empty ArrayList is created and the elements of the array are added to the ArrayList using the add() method within a loop. This approach offers greater flexibility than the previous methods, as you can modify or skip elements during the conversion process. However, it may be more verbose and prone to errors, especially for large arrays. This method is useful when fine-grained control is required during the conversion process.

Code:

import java.util.ArrayList;
import java.util.List;
public class ArrayToArrayListExample {
  	public static void main(String[] args) { 
   	String[] arr = {"apple", "banana", "cherry"}; 
  	List<String> list = new ArrayList<>(); 
  	for (String element : arr) {
  	list.add(element);
  	 } 
        System.out.println("Original Array: " + String.join(", ", arr));
        System.out.println("ArrayList: " + list); 
        list.add("date");
        System.out.println("Modified ArrayList: " + list);
    }
}

Output:

Original Array: apple, banana, cherry
ArrayList: [apple, banana, cherry]
Modified ArrayList: [apple, banana, cherry, date]

Code Explanation:

  • The code creates a string array of three elements (“apple”, “banana”, “cherry”) and assigns it to the variable arr.
  • An empty ArrayList is created and assigned to the variable list.
  • A for loop is used to iterate over the elements in the arr array, and each element is added to the list ArrayList using the list.add method.
  • The original array arr and the resulting ArrayList list are printed to the console using the System.out.println method.
  • A new element “date” is added to the ArrayList using the list.add method.
  • The modified ArrayList is printed to the console using the System.out.println method.
  • The output shows the original array, the ArrayList created from it, and the modified ArrayList with the added element “date”.

Best Approach to convert array to arraylist using Arrays.asList() :

The approach of using ‘Arrays.asList()’ to convert an array to a List, and then creating an ArrayList from that list, is a commonly used approach because it is simple, concise, and efficient.

Here are some reasons why this approach is considered one of the best:

  • It is easy to use: The ‘Arrays.asList()’ method is easy to use and requires only one line of code to convert an array to a List.
  • It is memory efficient: By using ‘Arrays.asList()’, we can avoid creating a new ArrayList and instead create a List view of the original array. This is memory efficient because it does not require additional memory to store the converted List.
  • It is fast: This approach is also fast because it does not require copying the elements of the array to a new ArrayList. Instead, it simply creates a List view of the original array and creates a new ArrayList that points to that list.

Sample Problems For Converting an array to an ArrayList in Java

Sample Problem 1:

Let’s say we have a program that reads from a file a list of student names and their grades. We want to send the sorted list to the console and sort the students according to their grades in descending order. However, in order to sort the list, we need to dynamically resize the data structure because the data is stored in an array.

Solution:

Code:

import java.util.ArrayList;
import java.util.Collections;
public class StudentSorterExample {
    public static void main(String[] args) {
        // Create an array of student names and their grades
        String[] students = { "Alice", "Bob", "Charlie", "David", "Emily" };
        int[] grades = { 90, 85, 95, 80, 88 };
        // Convert the arrays to ArrayLists
        ArrayList<String> studentList = new ArrayList<>();
        ArrayList<Integer> gradeList = new ArrayList<>();
        for (int i = 0; i < students.length; i++) {
            studentList.add(students[i]);
            gradeList.add(grades[i]);
        }
        // Sort the ArrayLists by grade in descending order
        Collections.sort(gradeList, Collections.reverseOrder());
        ArrayList<String> sortedStudentList = new ArrayList<>();
        for (int i = 0; i < gradeList.size(); i++) {
            int index = gradeList.indexOf(gradeList.get(i));
            sortedStudentList.add(studentList.get(index));
            gradeList.set(index, -1);
        }
        // Print out the sorted list of students and their grades
        for (int i = 0; i < sortedStudentList.size(); i++) {
            System.out.println(sortedStudentList.get(i) + ": " + gradeList.get(i));
        }
    }
}

Output:

Charlie: 95
Alice: 90
Emily: 88
Bob: 85
David: 80

Solution:

  • The code creates two arrays, one containing student names and another containing their grades.
  • Two empty ArrayLists are created, one for student names and one for grades.
  • A for loop is used to iterate over the elements in the arrays, and each element is added to its corresponding ArrayList using the add method.
  • The gradeList ArrayList is sorted in descending order using the Collections.sort method and the reverseOrder Comparator.
  • Another ArrayList called sortedStudentList is created to store the sorted list of student names.
  • A for loop is used to iterate over the gradeList ArrayList, and for each grade, the corresponding index in the studentList ArrayList is found and the student name is added to the sortedStudentList ArrayList.
  • After each student name is added, the grade at the corresponding index in gradeList is set to -1 to prevent duplicate entries.
  • A final for loop is used to iterate over the sortedStudentList and gradeList ArrayLists, and each student’s name and grade are printed to the console using the System.out.println method.
  • The output shows the sorted list of students and their grades in descending order.

Sample Problem 2:

You are working on a project that requires you to manipulate a list of books. The book data is stored in an array, but you need to use an ArrayList to perform operations like adding and removing books. You also need to filter the book list based on certain criteria.

Solution:To solve this problem, you can convert the array to an ArrayList using the Arrays.asList() method. Here’s an example code snippet that demonstrates how to do this:

Code:

import java.util.ArrayList;
import java.util.Arrays;
class Book {
    String title;
    String author;
    int yearPublished;
    public Book(String title, String author, int yearPublished) {
        this.title = title;
        this.author = author;
        this.yearPublished = yearPublished;
    }
    public String toString() {
        return title + " by " + author + " (" + yearPublished + ")";
    }
}
public class BookManager {
    public static void main(String[] args) {
        // Assume book data is read into an array called bookData
        String[][] bookData = {{"The Great Gatsby", "F. Scott Fitzgerald", "1925"},
                               {"To Kill a Mockingbird", "Harper Lee", "1960"},
                               {"1984", "George Orwell", "1949"}};
                // Convert the array to an ArrayList
        ArrayList<String[]> bookList = new ArrayList<>(Arrays.asList(bookData));
        // Convert the ArrayList of String[] to an ArrayList of Book objects
        ArrayList<Book> books = new ArrayList<>();
        for (String[] book : bookList) {
            String title = book[0];
            String author = book[1];
            int yearPublished = Integer.parseInt(book[2]);
            books.add(new Book(title, author, yearPublished));
        }    
        // Filter the book list to only include books published before 1960
        ArrayList<Book> oldBooks = new ArrayList<>();
        for (Book book : books) {
            if (book.yearPublished < 1960) {
                oldBooks.add(book);
            }
        }
        // Print the old book list to the console
        for (Book book : oldBooks) {
            System.out.println(book);
        }
    }
}

Output:

The Great Gatsby by F. Scott Fitzgerald (1925)


Explanation:
A Book class is defined with a constructor that initializes its properties (title, author, and yearPublished), and a toString() method that returns a string representation of a book object.

  1. In the main method, bookData is an array of string arrays that stores book information (title, author, and yearPublished) in each row.
  2. The bookData array is converted to an ArrayList of string arrays (bookList) using Arrays.asList() method.
  3. The bookList ArrayList is then converted to an ArrayList of Book objects (books) by iterating through each string array, extracting the book information, and creating a new Book object using that information.
  4. The books ArrayList is then filtered to only include books published before 1960, creating a new ArrayList called oldBooks.
  5. The oldBooks ArrayList is printed to the console using a for-each loop to iterate through each book object and calling its toString() method.

The output shows :

The Great Gatsby by F. Scott Fitzgerald (1925)

Sample Problem 3:

Let’s say we have an application that reads in a list of stock prices for a particular company from a file. We want to calculate the average stock price for the company over the past year, but the data is stored in an array and we need to resize the data structure dynamically to calculate the average.

Solution:

Code:

import java.util.ArrayList;
public class StockPriceExample {
    public static void main(String[] args) {
        // Create an array of stock prices
        double[] prices = { 100.0, 110.0, 95.0, 105.0, 120.0, 130.0, 125.0, 140.0, 135.0, 150.0, 145.0, 160.0 };
        // Convert the array to an ArrayList
        ArrayList<Double> priceList = new ArrayList<>();
        for (int i = 0; i < prices.length; i++) {
            priceList.add(prices[i]);
        }
        // Calculate the average stock price
        double sum = 0.0;
        for (int i = 0; i < priceList.size(); i++) {
            sum += priceList.get(i);
        }
        double average = sum / priceList.size();
        // Print out the average stock price
        System.out.println("Average stock price: " + average);
    }
}

Output:

Average stock price: 120.41666666666667

Explanation:
This code is an example of how to calculate the average stock price of an array of stock prices using an ArrayList. Here is a breakdown of the code and its output:

  • An array of stock prices is created with the following values:

{ 100.0, 110.0, 95.0, 105.0, 120.0, 130.0, 125.0, 140.0, 135.0, 150.0, 145.0, 160.0 }

  • The array is converted to an ArrayList called priceList.
  • The code then loops through the ArrayList to calculate the sum of all the prices.
  • The average price is calculated by dividing the sum by the number of prices in the ArrayList.
  • The average price is then printed to the console with the following message: “Average stock price: 120.41666666666667”.

Conclusion:

In Java, converting an array to an ArrayList can be accomplished using different approaches. Each approach has its own advantages and disadvantages, and the choice of the best approach depends on the specific requirements of the use case.
The Arrays.asList() method is simple and efficient but may not work with arrays of primitive types. The Collections.addAll() method is also simple and efficient but does not preserve the order of the original array. Iterating over each element in the array using a loop is a simple and effective approach for smaller arrays or when order is important but may not be as efficient for larger arrays.

The best approach depends on the specific requirements of the use case, including the size and type of array, and the importance of preserving order. By carefully considering these factors, it is possible to choose the most appropriate method for the task at hand.