Home >Java >javaTutorial >What are the methods to convert array to List in Java?

What are the methods to convert array to List in Java?

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2024-01-26 15:42:40775browse

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.

What are the methods to convert array to List in Java?

In Java, you can use the following methods to convert an array to a List:

  1. Use the asList() static method of the Arrays class
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));
  1. Use a for loop to traverse the array and add it to the List one by one
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.

  1. Using the Stream API of Java 8
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!

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
Previous article:How to use Java genericsNext article:How to use Java generics