149

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

14 Answers 14

342

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]
Sign up to request clarification or add additional context in comments.

9 Comments

+1: The new ArrayList<String>() may be redundant depending on how it is used. (as it is in your example ;)
Hehe, yeah, +1 :-) It may actually even just be the split his after :P
He would have to use Arrays.toString() to print it, but yes.
The new ArrayList<String>() causes a new list to be created with the returned list inside of it. Arrays.asList(a) returns a List object thus don't call new ArrayList you will get unwanted behavior.
Note that you can't add elements to the list returned by Arrays.asList. The OP wanted to have an ArrayList (which is completely reasonable) and the the ArrayList construction is necessary.
|
36
 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());

2 Comments

If you have to trim brackets, you could do it in one step with replace = s1.replaceAll("^\\[|]$", "");
I used this answer, but my user sometimes uses "," and others ", " as separators, so I added a .replaceAll(", ", ",") before split function.
18

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

1 Comment

s.split("\\s*,\\s*") can be added for extra care
15

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

3 Comments

Why doesn't this work List<Character> word1 = new ArrayList<Character>(Arrays.asList(A[0].toCharArray())); I'm trying to get first String of an string array, and convert that string into charArray and that charArray to List<Character>
that's because, asList method in Arrays class takes only Object array, not primitive arrays. If you convert char[] to Character[] array it will work.
public static Character[] boxToCharacter(char[] charArray) { Character[] newArray = new Character[charArray.length]; int i = 0; for (char value : charArray) { newArray[i++] = Character.valueOf(value); } return newArray; }
8

Easier to understand is like this:

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

Comments

4

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

Comments

2

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

Comments

2

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

Comments

2

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

Comments

1

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

1 Comment

A simpler character based approach would be: ArrayList<String> myList = new ArrayList<String>(); for(Character c :s.toCharArray() ) { myList.add(c.toString()); } But I don't think this is what the person is looking for. The solution by aioobe is what is required. cheers
1

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

1 Comment

so... you are using the accepted solution to make an example about a different problem? why?
0

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

Comments

0

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

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

Comments

0
String value = "java spring springboot microservices";

ArrayList<String> listValue = new ArrayList<>(Arrays.asList(value.split(" "));

1 Comment

You need to explain your code, so beginners reading it will have an easy time understanding it. An answer should consist educatory information, which is even more important than the solution itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.