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

How to convert array to list collection in java?

青灯夜游
青灯夜游Original
2020-10-27 15:21:0260603browse

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"};

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 resultList = new ArrayList<>(array.length);
for (String s : array) {
    resultList.add(s);
}

2. Use Arrays.asList()

List resultList= new ArrayList<>(Arrays.asList(array));

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 resultList = new ArrayList<>(array.length);
Collections.addAll(resultList,array);

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 resultList = List.of(array);

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!

Statement:
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