Home >Java >javaTutorial >What are the methods to convert array to List in Java?
There are three methods for converting arrays to List in Java: "asList(static method", "for loop traversal", and "Java 8's Stream API": 1. Use the asList() static method of the Arrays class , returns a fixed-length List, which cannot be added or deleted; 2. Use a for loop to traverse the array and add it to the List one by one; 3. Use the Stream API introduced in Java 8.
In Java, you can use the following methods to convert an array to a List:
String[] array = {"apple", "banana", "orange"}; List<String> list = Arrays.asList(array);
This method is the most commonly used one and can quickly convert an array into a List. It should be noted that the asList() method returns a fixed-length List and cannot be added or deleted. .If you need to modify the List, you can do so by creating a new ArrayList object:
String[] array = {"apple", "banana", "orange"}; List<String> list = new ArrayList<>(Arrays.asList(array));
String[] array = {"apple", "banana", "orange"}; List<String> list = new ArrayList<>(); for (String item : array) { list.add(item); }
This method is more cumbersome, but it can flexibly control the order and conditions of addition.
String[] array = {"apple", "banana", "orange"}; List<String> list = Arrays.stream(array).collect(Collectors.toList());
This method uses the Stream API introduced by Java 8 The Stream API can easily complete the conversion from an array to a List, but it should be noted that the array must be converted to a Stream object before the Collectors.toList() method can be used.
The above is the detailed content of What are the methods to convert array to List in Java?. For more information, please follow other related articles on the PHP Chinese website!