1

Possible Duplicate:
Assigning an array to an ArrayList in Java
java: how to convert this string to ArrayList?
How to convert a String into an ArrayList?

I have this String :

["word1","word2","word3","word4"]

The above text is not an array, but a string returned from server via GCM (Google Cloud Messaging) communication. More specific, inside a GCM class i have this:

protected void onMessage(Context context, Intent intent) {

String message = intent.getExtras().getString("cabmate");

   }

The value of the String message is ["word1","word2","word3","word4"]

Is there a way to convert it in List or ArrayList in Java?

Community
  • 1
  • 1
user1732457
  • 177
  • 1
  • 2
  • 15
  • Oh wait, you right ... it more like http://stackoverflow.com/questions/7347856/how-to-convert-a-string-into-an-arraylist?rq=1 or http://stackoverflow.com/questions/3898548/java-how-to-convert-this-string-to-arraylist?rq=1 or ... – Brian Roach Jan 12 '13 at 03:19

3 Answers3

3
Arrays.asList(String[])

returns a List<String>.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1
String wordString = "[\"word1\", \"word2\", \"word3\", \"word4\"]";
String[] words = wordString.substring(1, wordString.length() - 2).replaceAll("\"", "").split(", ");
List<String> wordList = new ArrayList<>();
Collections.addAll(wordList, words);

This will do what you want. Do note that I purposely split on ", " to remove white space, it may be more prudent to call .trim() on each string in a for-each loop and then add to the List.

Alex DiCarlo
  • 4,851
  • 18
  • 34
1

Something like this:

/*
@invariant The "Word" fields cannot have commas in thier values or the conversion
to a list will cause bad field breaks. CSV data sucks...
*/
public List<String> stringFormatedToStringList(String s) {
  // oneliner for the win:
  return Arrays.asList(s.substring(1,s.length()-1).replaceAll("\"","").split(","));
  // .substring  removes the first an last characters from the string ('[' & ']')
  // .replaceAll removes all quotation marks from the string (replaces with empty string)
  // .split brakes the string into a string array on commas (omitting the commas)
  // Arrays.asList converts the array to a List
}
recursion.ninja
  • 5,377
  • 7
  • 46
  • 78