Home > Java > Javagetting Started > How to convert array to list collection in java?

How to convert array to list collection in java?

青灯夜游
Release: 2020-10-30 16:50:32
Original
60925 people have browsed it

How to convert an array into a list collection in java: 1. Use the native method and use a for() loop to split the array and add it to the List; 2. Use the Arrays.asList() method; 3 , use Collections.addAll() method; 4. Use List.of() method.

How to convert array to list collection in java?

Related recommendations: "Java Video Tutorial"

Problem Description: For the given array below , how to convert into List collection?

String[] array = {"a","b","c"};
Copy after login

Refer to stackoverflow to summarize the following writing methods:

1. Use the native method to split the array and add it to the List

List<String> resultList = new ArrayList<>(array.length);
for (String s : array) {
    resultList.add(s);
}
Copy after login

2. Use Arrays.asList()

List<String> resultList= new ArrayList<>(Arrays.asList(array));
Copy after login

Note: When calling Arrays.asList(), its return value type is ArrayList, but this ArrayList is an internal class of Array. When calling add(), an error will be reported: java.lang.UnsupportedOperationException, and the result will be Because a certain value in the array changes, a new ArrayList needs to be constructed again.

3. Use Collections.addAll()

List<String> resultList = new ArrayList<>(array.length);
Collections.addAll(resultList,array);
Copy after login

4. Use List.of()

This method is a new method for Java 9 and is defined in the List interface, and It is a static method, so it can be called directly from the class name.

List<String> resultList = List.of(array);
Copy after login

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to convert array to list collection in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template