Here are the methods to convert Array to List in Java:
Brute Force or Naive Method: In this process, an empty List is designed and all elements present of the Array are attached to it one by one.
Algorithm:
Get the Array to be transformed.
Build an empty List
Iterate over the items in the Array.
For all items, attach it to the List
Pass the formed List
Syntax:
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> List<T> convertArrayToList(T array[])
{
List<T> list = new ArrayList<>();
// Iterate over the array
for (T t : array) {
// Add all elements into the list
list.add(t);
}
return list;
}
public static void main(String args[])
{
// Create an Array
String array[] = { "Fire", "onFire",
"A Song" };
// Print the Array
System.out.println("Array: "
+ Arrays.toString(array));
// convert the Array to List
List<String>
list = convertArrayToList(array);
// Print the List
System.out.println("List: " + list);
}
}
Output:
Array: [Fire, onFire, A Song]
List: [Fire, onFire, A Song]
2. Using Arrays.asList() method: In this method, the Array is transferred as the parameter into the List constructor with the help of Arrays.asList() program.
Algorithm:
Syntax:
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> List<T> convertArrayToList(T array[])
{
List<T> list = Arrays.asList(array);
// Return the converted List
return list;
}
public static void main(String args[])
{
// Create an Array
String array[] = { "Fire", "onFire",
"A Song" };
// Print the Array
System.out.println("Array: "
+ Arrays.toString(array));
// convert the Array to List
List<String>
list = convertArrayToList(array);
// Print the List
System.out.println("List: " + list);
}
}
Output:
Array: [Fire, onFire, A Song]
List: [Fire, onFire, A Song]