Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String array to ArrayList [duplicate]

Tags:

java

People also ask

How to convert the String array to ArrayList in java?

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.

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.


Use this code for that,

import java.util.Arrays;  
import java.util.List;  
import java.util.ArrayList;  

public class StringArrayTest {

   public static void main(String[] args) {  
      String[] words = {"ace", "boom", "crew", "dog", "eon"};  

      List<String> wordList = Arrays.asList(words);  

      for (String e : wordList) {  
         System.out.println(e);  
      }  
   }  
}

new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

String[] words= new String[]{"ace","boom","crew","dog","eon"};
List<String> wordList = Arrays.asList(words);

in most cases the List<String> should be enough. No need to create an ArrayList

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

...

String[] words={"ace","boom","crew","dog","eon"};
List<String> l = Arrays.<String>asList(words);

// if List<String> isnt specific enough:
ArrayList<String> al = new ArrayList<String>(l);