Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert String[] to ArrayList<String> [duplicate]

People also ask

How will you convert a String array to an ArrayList?

To convert string to ArrayList, we are using asList() , split() and add() methods. The asList() method belongs to the Arrays class and returns a list from an array. The split() method belongs to the String class and returns an array based on the specified split delimiter.

How do you copy a String into an ArrayList?

1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc. 2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays. asList() method.

Can we convert String array to list in Java?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.


You can do the following:

String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

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

The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.


List myList = new ArrayList();
Collections.addAll(myList, filesOrig); 

You can loop all of the array and add into ArrayList:

ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
    files.add(file);
}

Or use Arrays.asList(T... a) to do as the comment posted.


You can do something like

MyClass[] arr = myList.toArray(new MyClass[myList.size()]);