[java] How to convert a String into an ArrayList?

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,.........";

This question is related to java string arraylist converter

The answer is


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


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])

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);

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
*/

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+")));

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());
     }

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;
}

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(","));

 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());

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

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

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);

Easier to understand is like this:

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to converter

No converter found capable of converting from type to type How to convert datetime to integer in python Convert Int to String in Swift Concatenating elements in an array to a string Decimal to Hexadecimal Converter in Java Calendar date to yyyy-MM-dd format in java ffmpeg - Converting MOV files to MP4 Java: How to convert String[] to List or Set Convert xlsx to csv in Linux with command line How to convert string to long