可能重复:
Assigning an array to an ArrayList in Java
java: how to convert this string to ArrayList?
How to convert a String into an ArrayList?
我有String
:
["word1","word2","word3","word4"]
上述文字不是数组,而是通过GCM(Google Cloud Messaging)通信从服务器返回的字符串。更具体地说,在GCM课程中我有这个:
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("cabmate");
}
String
消息的值为["word1","word2","word3","word4"]
有没有办法在Java中用List
或ArrayList
转换它?
答案 0 :(得分:3)
Arrays.asList(String[])
返回List<String>
。
答案 1 :(得分: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);
这将做你想要的。请注意我故意拆分", "
以删除空格,在for-each循环中为每个字符串调用.trim()
然后添加到List
可能更为谨慎。 / p>
答案 2 :(得分:1)
这样的事情:
/*
@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
}