How to convert a String into an ArrayList?

JavaStringArraylistConverter

Java Problem Overview


In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:

String s = "a,b,c,d,e,.........";

Java Solutions


Solution 1 - Java

Try something like

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

Demo:

String s = "lorem,ipsum,dolor,sit,amet";

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

System.out.println(myList);  // prints [lorem, ipsum, dolor, sit, amet]

This post has been rewritten as an article here.

Solution 2 - Java

 String s1="[a,b,c,d]";
 String replace = s1.replace("[","");
 System.out.println(replace);
 String replace1 = replace.replace("]","");
 System.out.println(replace1);
 List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
 System.out.println(myList.toString());

Solution 3 - Java

Option1:

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

Option2:

List<String> list = new ArrayList<String>(Arrays.asList("hello"));

In my opinion, Option1 is better because

  1. we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.

  2. its performance is much better (but it returns a fixed-size list).

Please refer to the documentation here

Solution 4 - Java

In Java 9, using **List#of**, which is an Immutable List Static Factory Methods, become more simpler.

 String s = "a,b,c,d,e,.........";
 List<String> lst = List.of(s.split(","));

Solution 5 - Java

Easier to understand is like this:

String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);

Solution 6 - Java

Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:

List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));

Solution 7 - Java

If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:

String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then

List allEds = new ArrayList(); Collections.addAll(allEds, array1);

Solution 8 - Java

You could use:

List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());

You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:

// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);

Solution 9 - Java

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
        charList.add(str.charAt(i));
    }
    return charList;
}

But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
        stringList.add(s);
    }
    return stringList;
}

Solution 10 - Java

This is using Gson in Kotlin

 val listString = "[uno,dos,tres,cuatro,cinco]"
 val gson = Gson()
 val lista = gson.fromJson(listString , Array<String>::class.java).toList()
 Log.e("GSON", lista[0])

Solution 11 - Java

Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .

    public class StringReverse1 {
    public static void main(String[] args) {
    	
    	String a = "Gini Gina  Proti";
    	
    	List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
    	
    	list.stream()
    	.collect(Collectors.toCollection( LinkedList :: new ))
    	.descendingIterator()
    	.forEachRemaining(System.out::println);
    	
    	
    
    }}
/*
The output :
i
t
o
r
P
 
 
a
n
i
G
 
i
n
i
G
*/

Solution 12 - Java

I recommend use the StringTokenizer, is very efficient

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

     StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
     while (token.hasMoreTokens()) {
           list.add(token.nextToken());
     }

Solution 13 - Java

If you're using guava (and you should be, see effective java item #15):

ImmutableList<String> list = ImmutableList.copyOf(s.split(","));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSameek MishraView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavaSameek MishraView Answer on Stackoverflow
Solution 3 - JavaAndyView Answer on Stackoverflow
Solution 4 - JavaRaviView Answer on Stackoverflow
Solution 5 - JavaAbayView Answer on Stackoverflow
Solution 6 - JavaGherbi HichamView Answer on Stackoverflow
Solution 7 - JavaAndyView Answer on Stackoverflow
Solution 8 - JavaAbuNassarView Answer on Stackoverflow
Solution 9 - JavadenolkView Answer on Stackoverflow
Solution 10 - JavaFelix A Marrero PentónView Answer on Stackoverflow
Solution 11 - JavaSoudipta DuttaView Answer on Stackoverflow
Solution 12 - JavaPhilippeView Answer on Stackoverflow
Solution 13 - JavasabujpView Answer on Stackoverflow