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