How to convert array to list in Java
To convert an array to a list in Java, you can use the Arrays.asList()
method. This method returns a fixed-size list backed by the specified array. Here's an example:
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);
Note that the returned list is unmodifiable, so you cannot add or remove elements from it. If you need a modifiable list, you can use the ArrayList constructor to create a new list and copy the elements from the array:
String[] array = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(array));
Alternatively, you can use the Collections.addAll()
method to add the elements of the array to an existing ArrayList:
String[] array = {"a", "b", "c"};
List<String> list = new ArrayList<>();
Collections.addAll(list, array);