Converting String array to java.util.List

一世执手 提交于 2019-12-17 17:25:48

问题


How do I convert a String array to a java.util.List?


回答1:


List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});

This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).

If you want a modifiable a List:

List<String> strings = 
     new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));

This will copy all elements from the source array into a new list (complexity: O(n))




回答2:


Use the static List list = Arrays.asList(stringArray) or you could just iterate over the array and add the strings to the list.




回答3:


import java.util.Collections;

List myList = new ArrayList();
String[] myArray = new String[] {"Java", "Util", "List"};

Collections.addAll(myList, myArray);



回答4:


First Step you need to create a list instance through Arrays.asList();

String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list

Then you need to pass 'list' instance to new ArrayList();

List<String> newList=new ArrayList<>(list);



回答5:


The Simplest approach:

String[] stringArray = {"Hey", "Hi", "Hello"};

List<String> list = Arrays.asList(stringArray);


来源:https://stackoverflow.com/questions/6026813/converting-string-array-to-java-util-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!