Converting List to Array Java

In Java, there are numerous instances where you must transform a list into an array. For example, a function only accepts an array as a parameter instead of a collection.

The List interface is responsible for tracking the collection’s order. Further, the latter is a Collection’s child interface. It’s a sorted collection of objects that can store duplicate values. In addition, the list supports positional access and insertion of members because the insertion order is preserved. Now that we’ve been given a list of strings, whether a LinkedList or an ArrayList, our goal is to convert it to an array of strings in Java utilizing various methods.

Methods

  • The toArray() method is used
  • The get() method is used
  • Streams introduction in Java 8

toArray() method

This method returns an Object[] array whose elements are in the same order as the list’s elements. When performing some actions, casting is used to indicate the type of each element.

It’s another technique to make an array out of a list. We can easily convert a list to an array by utilizing the toArray() method. In addition, the toArray() method returns an array containing all of the list’s elements. The entries in the returned array are in the same order as those in the list.

The toArray() method is available on the List object. This function takes an empty array as a parameter and converts the current list to an array before inserting it into the specified array. This approach can be divided into two categories.

  • toArray()
  • toArray(T[] arr)

The toArray() function of the List interface has the following syntax:

public <T> T[] toArray(T[] a)

The toArray() method takes an array as an input or none and produces an array containing all the list’s members. Let’s look at another example of converting a list to an array to see how you might use the toArray() method of the list. To convert a List object to an array, use the following code.

  • Make a List object out of it.
  • Toss in some extras(elements).
  • Make an empty array the same size as the ArrayList you just made.
  • Bypass the above-created array as an input to the toArray() function when converting the list to an array.
  • The final step is printing the array’s contents.

The examples below demonstrate converting a List of Strings and a List of Integers to an Array.

Converting list to array in Java (with examples)

import java.util.ArrayList;

public class ListToArrayConversion {
   public static void main(String args[]){
      ArrayList<String> computerList = new ArrayList<String>();
      computerList.add("HP");
      computerList.add("DELL");
      computerList.add("Chrome Book");

      System.out.println("List Contents ::"+list);
      String[] theArray = new String[list.size()];
      computerList.toArray(theArray);

      for(int i=0; i<myArray.length; i++){
         System.out.println("The item at the index "+i+" is ::"+theArray[i]);
      }
   }
}

Example: Converting a list to array of string in Java

import java.util.ArrayList;
import java.util.List;

public class ConvertingArrayListToArray {
    public static void main(String[] args) {
        List<String> fruitsList = new ArrayList<String>();
        fruitsList.add("Mango");
        fruitsList.add("Water Melon");
        fruitsList.add("Oranges");

        String[] fruitsArray = new String[itemList.size()];
        finalArray = fruitsList.toArray(fruitsArray);

        for(String s : finalArray)
            System.out.println(s);
    }
}

We can convert a List of Integers to an Array of Integers using the same method:

Example: Converting a list to array of integers in Java

import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {
    public static void main(String[] args) {
        List<Integer> listOfIntegers = new ArrayList<Integer>();
        listOfIntegers.add(99);
        listOfIntegers.add(67);
        listOfIntegers.add(28);

        Integer[] arrayOfIntegers = new Integer[listOfIntegers.size()];
        finalArray = listOfIntegers.toArray(arrayOfIntegers);

        for(Integer i : finalArray)
            System.out.println(i);
    }
}

Example: Creating a class to convert a list into an array

import java.io.*;  
import java.util.LinkedList;  
import java.util.List;  

class CodeConvertListToArray {  

  // The programs main() method

  public static void main(String[] args)  
  {  
    // creation of a linked list through the declaration of an object of List  
    List<String> namesList = new LinkedList<String>();  

    // using the lists's add() method to add elements in the linked list  
    namesList.add("Joan");  
    namesList.add("Brian");  
    namesList.add("Cartoon");  
    namesList.add("Mike");  
    namesList.add("Thompson");  

    // using the toArray() method for converting a list into an array  
    String[] arrayOfNames = namesList.toArray(new String[0]);  

    // printing every element in the given array  
    System.out.println("After converting List into an Array");  
    for (int j = 0; j < arrayOfNames.length; j++) {  
      System.out.println((j+1)+" arrays element  is "+arrayOfNames[j]);  
    }  
  }   
}  

toArray(T[] arr)

This form of the same technique accepts an array that has already been defined as a parameter.

When the array’s size is more significant than or equal to the list’s size, the list’s elements are added to the array. A new array will be constructed and filled if this is not the case. On the other hand, casting is unnecessary because the parameter’s type gives the type of the returned array. If any element in the list fails to be converted into the given type, an ArrayStoreException is produced.

import java.util.ArrayList;

public class ListToArray {

	public static void main(String[] args) {
    // A list of size 4 to be converted:
		ArrayList<Integer> list = new ArrayList<>();
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		
    // Declaring an array of size 4:
		Integer[] arr = new Integer[4];
		
    // Passing the declared array as the parameter:
    list.toArray(arr);
		
    // Printing all elements of the array:
    System.out.println("Printing 'arr':");
		for(Integer i: arr)
      System.out.println(i);

    // Declaring another array of insufficient size:
    Integer[] arr2 = new Integer[3];

    // Passing the array as the parameter:
    Integer[] arr3 = list.toArray(arr2);

    // Printing the passed array:
    System.out.println("\n'arr2' isn't filled because it is small in size:");
    for(Integer i: arr2)
      System.out.println(i);
    
    // Printing the newly allocated array:
    System.out.println("\n'arr3' references the newly allocated array:");
    for(Integer i: arr3)
      System.out.println(i);
	}
}

An array of Strings to List

You can also return from an Array to a List. We utilize Arrays.asList to accomplish this. Consider the following scenario:

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

public class ConvertingArrayToList {
    public static void main(String[] args) {
        String[] subjectsArray = {"Introduction to Programming", "Data structures and algorithms", "Advanced database management system", "Computer Ethics"};
        List<String> subjectsList = new ArrayList(Arrays.asList(subjectsArray));

        for (String subjecItem : subjectsList) {
            System.out.println(subjecItem);
        }
    }
}

get() method

The get() method is one of the most straightforward processes for converting a list to an array. We can now access all of the list elements one by one and add them to an array. The aim here is to use the get() method. We can use the list method below to get all elements and insert them into an array.

Return Type: The element in the list at the index specified.

The get() function of the List interface has the following syntax:

public E get(int index)

The element at the provided position in the list is returned by the get() method. Let’s look at an example of converting a list to an array to see how we may use the list’s get() method.

Example: Java program for converting a list to an array

// Using get() method in a loop

// Importing required classes
import java.io.*;
import java.util.LinkedList;
import java.util.List;

// Main class
class Codeunderscored {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating a LinkedList of string type by
		// declaring object of List
		List<String> listOfProgrammingLanguagues = new LinkedList<String>();

		// Adding custom element to LinkedList
		// using add() method
		listOfProgrammingLanguagues.add("PHP");
		listOfProgrammingLanguagues.add("C++");
		listOfProgrammingLanguagues.add("Python");
		listOfProgrammingLanguagues.add("Java");

		// Storing it inside array of strings
		String[] arrVal = new String[list.size()];

		// Conversion of an ArrayList to Array using the get() method
		for (int i = 0; i < listOfProgrammingLanguagues.size(); i++)
			arrVal[i] = listOfProgrammingLanguagues.get(i);

		// print the given elements of array on the console
		for (String str : arr)
			System.out.print( str + " ");
	}
}

Example: Class to convert a list into an array

import java.io.*;  
    import java.util.LinkedList;  
    import java.util.List;  

    // create ListToArrayConversionExample class to convert a list into an array  
    class ListToArrayConversionExample {  
        // The programs main() method 
        public static void main(String[] args)  
        {  
             // creation of a  linked list through the declaration of an object of List  
             List<String> javaStudents = new LinkedList<String>();  
             // using the add() method of the list to add elements in the linked list  
             javaStudents.add("Ann");  
             javaStudents.add("Abraham");  
             javaStudents.add("Winny");  
             javaStudents.add("Bob");  
             javaStudents.add("Princes");  

             // get the lists' size and store it into lenOfList variable  
             int lenOfList = javaStudents.size();  
            
	 // declaration and the initialization of the array of type string to store list elements  
             String[] javaStudentsArray = new String[ lenOfList ];  
             // iterating through the list through the for loop and add all the elements into javaStudentsArray one by one to convert names list into an array  
             for (int i = 0; i < len; i++)  
                 javaStudentsArray[i] = javaStudents.get(i);  
             // print all the elements of the array  
             System.out.println("Conversion of a List into an Array");  
             for (int j = 0; j < javaStudentsArray.length; j++) {  
                 System.out.println((j+1)+" array element is : "+javaStudentsArray[j]);  
             }  
        }   
    }  

Using the Stream class – introduced in Java8

Another approach is to convert a List to an array, using the Stream feature introduced in Java8. The toArray() function of the List interface has the following syntax:

public <T> T[] toArray(T[] a)

The toArray() method takes either an array or none as an argument. Furthermore, it returns an array that contains all of the list’s elements. The Stream.toArray() method returns an array containing the stream entries from the List.stream() method. There are two options for doing so:

Using Streams in conjunction with a method reference

List<String> languageList = Arrays.asList("Python","Kotlin", "C++","JavaScript", "Java");
String[] languageArray = languageList.stream().toArray(String[]::new);
System.out.println(Arrays.toString(languageArray));

Using lambda expressions with streams

List<String> languageList = Arrays.asList("Python","Kotlin", "C++","JavaScript", "Java");
String[] languageArray = languageList.stream().toArray(n -> new String[n]);
System.out.println(Arrays.toString(languageArray));

Let’s look at another example of converting a list to an array to see how you might use the toArray() method of the list.

import java.io.*;  
import java.util.LinkedList;  
import java.util.List;  

//create ListToArrayConversion class to convert a list into an array  
class ListToArrayConversion {  
  // The programs main() method
  public static void main(String[] args)  
  {  
    // creation of a linked list through the declaration of an object of List  
    List<String> listOfNames = new LinkedList<String>();  
    // using the lists's add() method to add elements in the linked list  

    listOfNames.add("Jonah");  
    listOfNames.add("Mike");  
    listOfNames.add("Ann");  
    listOfNames.add("Faith");  
    listOfNames.add("Mery");  

    // using the stream() method to convert a list into an array  
    String[] arrayOfNames = listOfNames.stream().toArray(String[] ::new);  

    // print all the elements of the array  
    System.out.println("Results after converting a List into an Array");  
    for (int j = 0; j < arrayOfNames.length; j++) {  
      System.out.println((j+1)+" The array's element is: "+arrayOfNames[j]);  
    }  
  }   
}  

Example: Program demonstrating the conversion of List to Array using stream

// Importing utility classes
import java.util.*;

// Main class
class CodeunderscoredStream {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating an empty LinkedList of string type
		List<String> listLaptops = new LinkedList<String>();

		// Adding elements to above LinkedList
		// using add() method
		listLaptops.add("HP");
		listLaptops.add("Dell");
		listLaptops.add("Apple");
		listLaptops.add("IBM");
		listLaptops.add("Lenovo");
		listLaptops.add("Chrome Book");

		// Storing size of List
		int listSize = listLaptops.size();

		// Converting List to array via scope resolution
		// operator using streams
		String[] arrOfStreams = listLaptops.stream().toArray(String[] ::new);

		// Printing elements of array
		// using enhanced for loop
		for (String str : arrOfStreams)
			System.out.print(str + " ");
	}
}

Using the Guava Library

There are two variations of using the Guava Library as follows.

The FluentIterable class in the Guava Library

The FluentIterable is an extended Iterable API that provides similar capabilities to Java 8’s streams library slightly differently. The goal is to create a fluent iterable that wraps an iterable list and produces an array with all its items in the iteration sequence.

List<String> languagesList = Arrays.asList("Python","Kotlin", "C++","JavaScript", "Java");
String[] languageArray = FluentIterable.from(languagesList).toArray(String.class);
System.out.println(Arrays.toString(languageArray));

The Iterables class in the Guava Library

The toArray() function of Guava’s Iterables class copies the items of an iterable into an array.

List<String> languagesList = Arrays.asList("Python","Kotlin", "C++","JavaScript", "Java");
String[] languageArray = Iterables.toArray(languagesList, String.class);
System.out.println(Arrays.toString(languageArray));

Example: using Guava

@Test
public void givenUsingGuava() {
    Integer[] numArray = { 10, 11, 12, 13, 14, 15 };
    List<Integer> resultantList = Lists.newArrayList(numArray);
}

Making Use of Commons Collections

Finally, we’ll use CollectionUtils from Apache Commons Collections. To fill up the elements of an array in an empty List, use the addAll API:

@Test
public void usingCommonsCollections() {
    Integer[] numArray = { 10, 11, 12, 13, 14, 15 };
    List<Integer> resultantList = new ArrayList<>(6);
    CollectionUtils.addAll(resultantList, numArray);
}

Conclusion

In Java, converting between List and Array is a typical task. The .toArray() function is the finest and most straightforward way to transform a List into an Array in Java. Similarly, we may use the Arrays.asList() method to convert a List back to an Array. In addition, we may also use the stream() method of the Stream API to convert a list to an array in Java 8 and later.

Also, in Java, the get() and toArray() methods commonly transform a list into an array. In comparison to the get() and toArray() methods, the stream() technique is inefficient.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *