113

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,.........";
President James K. Polk
  • 36,717
  • 16
  • 86
  • 116
Sameek Mishra
  • 8,234
  • 28
  • 86
  • 113

13 Answers13

275

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.

aioobe
  • 383,660
  • 99
  • 774
  • 796
  • 9
    +1: The `new ArrayList()` may be redundant depending on how it is used. (as it is in your example ;) – Peter Lawrey Sep 08 '11 at 13:42
  • 1
    Hehe, yeah, +1 :-) It may actually even just be the `split` his after :P – aioobe Sep 08 '11 at 13:47
  • He would have to use `Arrays.toString()` to print it, but yes. – Peter Lawrey Sep 08 '11 at 13:58
  • The new ArrayList() 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. – Clocker Nov 14 '14 at 16:51
  • 6
    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. – aioobe Nov 14 '14 at 17:37
  • is that posibble to convert string to byte with this method? – mehmet Feb 12 '18 at 15:38
  • @mehmet, no. Use `String.getBytes`. – aioobe Feb 12 '18 at 17:42
34
 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());
Bilesh Ganguly
  • 3,000
  • 2
  • 31
  • 50
Sameek Mishra
  • 8,234
  • 28
  • 86
  • 113
  • 10
    If you have to trim brackets, you could do it in one step with `replace = s1.replaceAll("^\\[|]$", "");` – David Ehrmann Oct 31 '16 at 15:21
  • I used this answer, but my user sometimes uses `","` and others `", "` as separators, so I added a `.replaceAll(", ", ",")` before `split` function. – IgniteCoders Oct 29 '20 at 13:15
9

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

Andy
  • 2,911
  • 5
  • 17
  • 30
  • Why doesn't this work ```List word1 = new ArrayList(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 – sofs1 Apr 19 '19 at 22:55
  • 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. – Andy Apr 21 '19 at 18:15
  • 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; } – Andy Apr 21 '19 at 18:15
8

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(","));
Ravi
  • 28,657
  • 41
  • 110
  • 158
3

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+")));
Gherbi Hicham
  • 2,007
  • 4
  • 21
  • 35
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);
No Idea For Name
  • 10,935
  • 10
  • 37
  • 61
Andy
  • 169
  • 1
  • 2
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);
AbuNassar
  • 878
  • 8
  • 12
1

Easier to understand is like this:

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

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])
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;
}
denolk
  • 751
  • 14
  • 24
  • A simpler character based approach would be: ArrayList myList = new ArrayList(); 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 – Steve Sep 08 '11 at 13:30
0

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
*/
Soudipta Dutta
  • 602
  • 6
  • 5
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());
     }
Philippe
  • 327
  • 2
  • 17
0

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

ImmutableList<String> list = ImmutableList.copyOf(s.split(","));
sabujp
  • 791
  • 1
  • 9
  • 11