0 0
WP Ad Inserter plugin
Read Time:11 Minute, 5 Second

Table of Contents

The two most significant data structures in Java are Array and List. We’ll learn how to convert a Java Array to a List in this section. We’ve also written Java applications that use several Java techniques to turn an Array into a List.

Java array to list conversion

An array in Java is a container for multiple values of the same data type. Objects and primitive types can both be stored in an array. The array’s definition determines it. The array’s values are stored in the same memory address if the array definition is of primitive type. If a collection contains object elements, the heap section is used to store them.

A List is a collection of interfaces in Java that belong to the Java Collections framework. It maintains the insertion order while storing elements in the form of objects in an orderly way. Further, it enables us to keep track of duplicate values.

The List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. The following are the five methods available in Java for converting an Array to a List:

  • Native Method or the Brute force method
  • Using Arrays.asList() Method
  • Using Collections.addAll() Method
  • Using Java 8 Stream API
  • Using Guava Lists.newArrayList() Method

Using the native method

It is the most straightforward way to convert a Java Array to a List. In this technique, we first build an empty List and then add all of the array’s elements to it. Let’s have a look at an example.

SUGGESTED READ

 import java.util.*; public class ArrayToList
{ public static void main(String args[]) { //creating an array String languageArray[] = { "PHP", "JavaScript", "Python", "Kotlin", "Java", "C++", "Ruby", "Swift", "Go"}; //prints the array before conversion System.out.println("Languages Array before conversion: "+ Arrays.toString(languageArray)); //call to the generic method responsible for converting Array into List List<String> languagesList = ArrayToListConversion(languageArray); //print the Languages List System.out.println("Languages Array as List: " + languagesList); } //call to the generic method responsible for converting Array into List public static <T> List<T> ArrayToListConversion(T array[]) { //creating the constructor of the List class List<T> langList = new ArrayList<>(); //using the for-each loop in iterating throught the array elements for (T t : languageArray) { //adding each element to the List langList.add(t); } //returns the list converted into Array return list; } } 

Using arrays.asList() method

It’s a method in the Java Arrays class, which is part of the Java.util package. When we combine the asList() and Collection.toArray() methods, we have a bridge between array- and collection-based APIs.

The syntax is as follows:

public static <T> List<T> asList(T... a)

The method takes an array as a parameter, which is used to back up the langList. The supplied array is returned as a serializable fixed-size list view. Let’s have a look at an example.

import java.util.*; public class ArrayToList
{ public static void main(String args[]) { //creating an array to be converted String languageArray[] = { "PHP", "JavaScript", "Python", "Kotlin", "Java", "C++", "Ruby", "Swift", "Go"}; //prints array before conversion System.out.println("Language Array before conversion: "+ Arrays.toString(languageArray)); //call to the generic method responsible for converting Array into List List<String> langList = ArrayToListConversion(languageArray); //prints the List System.out.println("Language Array after conversion: " + langList); } // Generic function responsible for converting an array to a list public static <T> List<T> ArrayToListConversion(T arr[]) { //invoke the method asList() and pass the array to be converted List<T> langList = Arrays.asList(languageArray); //returns the list return langList; } } 

Using collections.addAll() method

It’s the Java Collections class’s function. It’s part of the Java.util package. addAll() is a method provided by the class. The method can be used to transform an Array into a List. It populates the provided collection with all of the elements. Elements can be specified singly or in the form of an array. It’s the same as Arrays.asList(elements) + c.addAll(Arrays.asList(elements) + c.addAll(Arrays.asList(elements))

It is a quicker implementation than the previous one.

SUGGESTED READ

The syntax is as follows:

public static <K> boolean addAll(Collection<? super K> c, K... elements) 

It takes two parameters into account:

  • c: It’s a set of elements that need to be added to.
  • elements: The elements must be placed in c.

If the collection changed due to the call, it returns true. The following exceptions are thrown:

  • UnsupportedOperationException is thrown if the parameter c does not support the add operation.
  • NullPointerException is thrown if one or more of the provided array members have null values, and c does not allow null elements.
  • IllegalPointerException is thrown if any array element prohibits it from being inserted into the parameter c.

Let’s have a look at an example.

import java.util.*; public class ArrayToListExample3 { public static void main(String args[]) { //creating an Array to be converted String languageArray[] = { "PHP", "JavaScript", "Python", "Kotlin", "Java", "C++", "Ruby", "Swift", "Go"}; //prints the Array System.out.println("Languages Array before conversion: "+ Arrays.toString(languageArray)); //method calling List<String> langList = ArrayToListConversion(languageArray); //print the List System.out.println("Languages Array after conversion: " + langList); } //call to the generic method responsible for converting Array into List public static <T> List<T> ArrayToListConversion(T arr[]) { //creating the constructor of thr List class List<T> langList = new ArrayList<>(); //the method adds Array to the List Collections.addAll(langList, languageArray); //returns the langList return langList; } } 

Using the Stream API in Java 8

The Stream API in Java 8 allows you to manipulate collections of objects. It’s a set of methods that can be piped together to get the desired outcome. It’s important to remember that the original data structure isn’t affected. It generates the output using pipelined methods. You can obtain the stream in a variety of ways. However, in the following example, we’ve used Arrays.stream(Object[]) to do it.

SUGGESTED READ

In an encounter method, the Collectors.toList() method returns a Collector that aggregates the input components into a newly generated List.

The syntax is as follows:

public static <K> Collector<K,?,List<K>> toList() 

Where K denotes the element type we’ve provided. The method does not provide type, mutability, thread safety, or serializability guarantees. Let’s utilize the Stream API to convert an array to a List in a Java program.

import java.util.*; import java.util.stream.Collectors; public class ArrayToList { //call to the generic method responsible for converting Array into List public static <T> List<T> ArrayToListConversion(T arr[]) { //is responsible for creating a list from the Array given and returns a corresponding List return Arrays.stream(arr).collect(Collectors.toList()); } public static void main(String args[]) { //array creation to convert into a List String languageArray[] = { "PHP", "JavaScript", "Python", "Kotlin", "Java", "C++", "Ruby", "Swift", "Go"}; //prints the Array before conversion System.out.println("Array: "+ Arrays.toString(languageArray)); //call to the method created above and storing the elements into the List object List<String> langList = ArrayToListConversion(languageArray); //prints the langList System.out.println("List: " + langList); } } 

Using Guava Lists.newArrayList()

Guava Lists are a great way to organize your data. It belongs to the com.google.common.collect package and is a method of the Lists class. The newArrayList() method of the class generates a mutable empty ArrayList object with the elements of the supplied array.

The syntax is as follows:

SUGGESTED READ

public static <E> ArrayList<E> newArrayList(E... elements)

For Java 6 and previous versions, the newArrayList() method is available. It is deprecated in newer versions. We utilize the ArrayList constructor directly instead of the above technique.

import static com.google.common.collect.Lists.*; import java.util.*; public class ArrayToList { public static void main(String args[]) { //creation of an Array for conversion into a List String languageArray[] = { "PHP", "JavaScript", "Python", "Kotlin", "Java", "C++", "Ruby", "Swift", "Go"}; //prints the Array before conversion System.out.println("Array: "+ Arrays.toString(languageArray)); //convert the Array to List List<String> langList = ArrayToListConversion(languageArray); //prints the langList System.out.println("List: " + langList); } // Generic function responsible for converting an array to a list public static <T> List<T> ArrayToListConversion(T arr[]) { //creates a List from the specified Array return Lists.newArrayList(languageArray); } } 

Examples: Using the Brute force approach

// Program for converting an Array to a List import java.util.*;
import java.util.stream.*; class Codeunderscored { // Generic function responsible for converting an array to a list public static <T> List<T> codeConvertArrayToList(T array[]) { // empty List creation List<T> list = new ArrayList<>(); // Iterate through the array for (T t : array) { // Add each element into the list list.add(t); } // Return the converted List return list; } public static void main(String args[]) { // Create an Array String laptopsArray[]= { "Chromebook", "DELL", "Apple", "HP", "Toshiba" }; // Print the Array System.out.println("Array: "+ Arrays.toString(array laptopsArray // convert the Array to List List<String> laptopsList = convertArrayToList(laptopsArray); // Print the List System.out.println("List of Laptops: " + laptopsList); }
}

Example: using Using Arrays.asList() Method

// Java Program to convert
// Array to List import java.util.*;
import java.util.stream.*; class Codeunderscode { // Generic function responsible for converting an array to a list public static <T> List<T> codeConvertArrayToList(T array[]) { // pass the array as parameter in the constructor to create the list List<T> list = Arrays.asList(array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String laptopsArray[]= { "Chromebook", "DELL", "Apple", "HP", "Toshiba" }; // Print the Array System.out.println("Array: "+ Arrays.toString(array laptopsArray // convert the Array to List List<String> laptopsList = convertArrayToList(laptopsArray); // Print the List System.out.println("List of Laptops: " + laptopsList); }
}

Example: Using Collections.addAll()

// Java Program to convert
// Array to List import java.util.*;
import java.util.stream.*; class Codeunderscored { // Generic function responsible for converting an array to a list public static <T> List<T> codeConvertArrayToList(T array[]) { // pass the array as parameter in the constructor to create the list List<T> list = new ArrayList<>(); // Add the array to list Collections.addAll(list, array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String laptopsArray[]= { "Chromebook", "DELL", "Apple", "HP", "Toshiba" }; // Print the Array System.out.println("Array: "+ Arrays.toString(array laptopsArray // convert the Array to List List<String> laptopsList = convertArrayToList(laptopsArray); // Print the List System.out.println("List of Laptops: " + laptopsList); }
}

Example: Using Using Java 8 Stream API

// Java Program to convert
// Array to List in Java 8 import java.util.*;
import java.util.stream.*; class Codeunderscored { // Generic function responsible for converting an array to a list public static <T> List<T> codeConvertArrayToList(T array[]) { // list creation from an array return Arrays.stream(array).collect( Collectors.toList()); } public static void main(String args[]) { // Creation of an Array String laptopsArray[]= { "Chromebook", "DELL", "Apple", "HP", "Toshiba" }; // Print the Array System.out.println("Array: "+ Arrays.toString(array laptopsArray // convert the Array to List List<String> laptopsList = convertArrayToList(laptopsArray); // Print the List System.out.println("List of Laptops: " + laptopsList); }
} 

Example: Using Using Guava Lists.newArrayList()

// Java Program to convert
// Array to List in Java 8 import static com.google.common.collect.Lists.*; import java.util.*;
import java.util.stream.*; class Codeunderscored { // Generic function responsible for converting an array to a list public static <K> List<K> convertArrayToList(K array[]) { // creation of a list from the Array return Lists.newArrayList(array); } public static void main(String args[]) { // Create an Array String laptopsArray[]= { "Chromebook", "DELL", "Apple", "HP", "Toshiba" }; // Print the Array System.out.println("Array: "+ Arrays.toString(array laptopsArray // convert the Array to List List<String> laptopsList = convertArrayToList(laptopsArray); // Print the List System.out.println("List of Laptops: " + laptopsList); }
}

Conclusion

An array points to a collection of similar-typed variables with a common name. Depending on the array’s definition, it can hold primitive data types and objects. The actual values of primitive data types are stored in contiguous memory regions. The real objects are stored in a heap section for objects of a class.

The collection has a child interface called List. It’s not just a sorted collection of objects, but it can also store duplicate values. In addition, the List supports positional access and insertion of members because the insertion order is preserved. Also, the ArrayList, LinkedList, Vector, and Stack classes implement the List Interface.

The Java Arrays class has a few useful methods. Arrays.asList() is a utility method that allows us to convert an Array of objects to a List of objects. The examples we have covered in this article demonstrate how to convert an array to a list object. Other approaches you can use include: The native method, using Collections.addAll() method, using Java 8 Stream API, and using Guava Lists.newArrayList() Method.

Source: https://www.codeunderscored.com/how-to-convert-array-to-list-in-java/

How to convert Array to List in Java Previous post How to convert Array to List in Java
Next post Reverse an array in Java explained with examples

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.