Converting Between an Array and List

JavaJavaBeginner
Practice Now

Introduction

Arrays are widely used linear data structures in Java for storing collections of data. They allow for random access to any element of the array using its index, as the elements are allocated in contiguous blocks of memory. On the other hand, the List interface provides a way to maintain an ordered collection of data, and is implemented by classes such as ArrayList and LinkedList. In this lab, we will learn how to convert an array to a list and vice versa using various methods in Java.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117399{{"`Converting Between an Array and List`"}} java/generics -.-> lab-117399{{"`Converting Between an Array and List`"}} java/arraylist -.-> lab-117399{{"`Converting Between an Array and List`"}} java/classes_objects -.-> lab-117399{{"`Converting Between an Array and List`"}} java/class_methods -.-> lab-117399{{"`Converting Between an Array and List`"}} java/modifiers -.-> lab-117399{{"`Converting Between an Array and List`"}} java/oop -.-> lab-117399{{"`Converting Between an Array and List`"}} java/packages_api -.-> lab-117399{{"`Converting Between an Array and List`"}} java/wrapper_classes -.-> lab-117399{{"`Converting Between an Array and List`"}} java/identifier -.-> lab-117399{{"`Converting Between an Array and List`"}} java/arrays -.-> lab-117399{{"`Converting Between an Array and List`"}} java/comments -.-> lab-117399{{"`Converting Between an Array and List`"}} java/data_types -.-> lab-117399{{"`Converting Between an Array and List`"}} java/for_loop -.-> lab-117399{{"`Converting Between an Array and List`"}} java/operators -.-> lab-117399{{"`Converting Between an Array and List`"}} java/output -.-> lab-117399{{"`Converting Between an Array and List`"}} java/strings -.-> lab-117399{{"`Converting Between an Array and List`"}} java/variables -.-> lab-117399{{"`Converting Between an Array and List`"}} java/system_methods -.-> lab-117399{{"`Converting Between an Array and List`"}} end

Converting Array to List using asList() Method

The asList() method of the Arrays class can be used to convert an array to a list. It takes the array as a parameter and returns a list of its elements. We will perform the following steps to convert an array to a list using the asList() method:

  • Create a string array and an integer array, and initialize them with values
  • Use the Arrays.asList() method to convert the arrays to lists
  • Print the lists
import java.util.Arrays;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 1: Converting Array to List using asList() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Converting arrays to lists using asList() method
        List<String> strList = Arrays.asList(strArr);
        List<Integer> intList = Arrays.asList(intArr);
        // Printing the lists
        System.out.println("Array to List using asList() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Converting Array to List using Collections.addAll() Method

The Collections.addAll() method can be used to add all the elements of an array to a list. We first need to create an empty list and then pass the existing array and the new list as parameters to this method. We will perform the following steps to convert an array to a list using the Collections.addAll() method:

  • Create a string array and an integer array, and initialize them with values
  • Create an empty list of the corresponding data types, using the ArrayList class
  • Use the Collections.addAll() method to add the elements of the arrays to the lists
  • Print the lists
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 2: Converting Array to List using Collections.addAll() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Creating empty lists of the corresponding data types
        List<String> strList = new ArrayList<String>();
        List<Integer> intList = new ArrayList<Integer>();
        // Using the Collections.addAll() method to add the elements of the arrays to the lists
        Collections.addAll(strList, strArr);
        Collections.addAll(intList, intArr);
        // Printing the lists
        System.out.println("Array to List using Collections.addAll() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Converting Array to List using Guava's Lists.newArrayList() Method

The Lists.newArrayList() method from the Guava library can also be used to convert an array to an ArrayList. We will perform the following steps to convert an array to a list using the Lists.newArrayList() method:

  • Create a string array and an integer array, and initialize them with values
  • Use the Lists.newArrayList() method to convert the arrays to ArrayLists
  • Print the ArrayLists
import com.google.common.collect.Lists;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 3: Converting Array to List using Guava's Lists.newArrayList() Method
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Creating an integer array
        Integer[] intArr = {2, 3, 5, 7, 11, 13, 17};
        // Converting arrays to ArrayLists using Guava's Lists.newArrayList() method
        List<String> strList = Lists.newArrayList(strArr);
        List<Integer> intList = Lists.newArrayList(intArr);
        // Printing the ArrayLists
        System.out.println("Array to List using Guava's Lists.newArrayList() Method: ");
        System.out.println(strList);
        System.out.println(intList);
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Writing our own method to convert Array to List

We can also write our own method to convert an array to a list. We will use the List interface's add() method to add elements from the array to the list. We will perform the following steps to write our own method:

  • Write a method that takes a string array as a parameter and returns a list of strings
  • Within the method, create an empty ArrayList
  • Loop through the array and add each element to the ArrayList using the add() method
  • Return the ArrayList
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    // Step 4: Writing our own method to convert Array to List
    public static List<String> arrayToList(String[] strArr) {
        List<String> strList = new ArrayList<String>();
        for(int i = 0; i <= strArr.length - 1; i++)
            strList.add(strArr[i]);
        return strList;
    }

    public static void main(String[] args) {
        // Creating a string array
        String[] strArr = {"this", "is", "a", "string", "array"};
        // Converting array to list using our own method
        List<String> strList = arrayToList(strArr);
        // Printing the list
        System.out.println("Array to List using our own method: ");
        System.out.println(strList);
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Converting List to Array using toArray() Method

The toArray() method can be used to convert a list to an array. It takes an array as a parameter, and returns an array containing the elements of the list. We will perform the following steps to convert a list to an array using the toArray() method:

  • Create an ArrayList and add elements to it
  • Use the toArray() method to convert the ArrayList to an array
  • Print the array
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 5: Converting List to Array using toArray() Method
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using toArray() method
        String[] strArr = strList.toArray(new String[0]);

        // Printing the array
        System.out.println("List to Array using toArray() Method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Converting List to Array using Guava's Iterables.toArray() Method

The Iterables.toArray() method from the Guava library can also be used to convert a list to an array. We will perform the following steps to convert a list to an array using the Iterables.toArray() method:

  • Create an ArrayList and add elements to it
  • Use the Iterables.toArray() method to convert the ArrayList to an array
  • Print the array
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Step 6: Converting List to Array using Guava's Iterables.toArray() Method
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using Guava's Iterables.toArray() method
        String[] strArr = Iterables.toArray(strList, String.class);

        // Printing the array
        System.out.println("List to Array using Guava's Iterables.toArray() Method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Writing our own method to convert List to Array

We can also write our own method to convert a list to an array. We will loop through the list and fetch each element using the get() method and add it to the array using the array indices. We will perform the following steps to write our own method:

  • Write a method that takes a list of strings as a parameter and returns a string array
  • Within the method, create an empty string array of size equal to the size of the list
  • Loop through the list and add each element to the array using array indices
  • Return the array
import java.util.ArrayList;
import java.util.List;

public class ArrayToList {
    public static String[] listToArray(List<String> strList) {
        String[] strArr = new String[strList.size()];
        for(int i = 0; i <= strList.size() - 1; i++)
            strArr[i] = strList.get(i);
        return strArr;
    }

    public static void main(String[] args) {
        // Writing our own method to convert List to Array
        // Creating an ArrayList
        List<String> strList = new ArrayList<String>();
        strList.add("this");
        strList.add("is");
        strList.add("a");
        strList.add("string");
        strList.add("array");

        // Converting ArrayList to array using our own method
        String[] strArr = listToArray(strList);

        // Printing the array
        System.out.println("List to Array using our own method: ");
        for(int i = 0; i <= strArr.length - 1; i++)
            System.out.print(strArr[i] + " ");
    }
}

To run the code, open the terminal, navigate to the project folder and type the following command: javac ArrayToList.java && java ArrayToList

Summary

In this lab, we explored various methods to convert an array to a list and a list back to an array in Java. We saw how we can use the asList() method of the Arrays class, the addAll() method of the Collections class, and the Lists.newArrayList() method from the Guava library to convert an array to a list. We also saw how we can use the toArray() method and the Iterables.toArray() method from the Guava library to convert a list to an array. Finally, we wrote our own methods to perform these conversions. Understanding the different methods of converting arrays to lists and vice versa can help us utilize the potential of both data structures and enhance our programming skills in Java.

Other Java Tutorials you may like