如何将字符串转换为ArrayList?
在我的字符串中,我可以有任意数量的以逗号分隔的单词。我希望将每个单词添加到 ArrayList 中。例如:
String s = "a,b,c,d,e,.........";
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,.........";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
尝试类似
Arrays.asList
文档String.split
文档ArrayList(Collection)
构造函数文档演示:
Try something like
Arrays.asList
documentationString.split
documentationArrayList(Collection)
constructor documentationDemo:
在 Java 9 中,使用
List#of
,它是一个不可变列表静态工厂方法,变得更加简单。In Java 9, using
List#of
, which is an Immutable List Static Factory Methods, become more simpler.选项1:
选项2:
在我看来,选项1更好,因为
asList
方法创建并返回一个 ArrayList 对象。请参阅文档 这里
Option1:
Option2:
In my opinion, Option1 is better because
asList
method creates and returns an ArrayList Object.Please refer to the documentation here
比较容易理解的是这样的:
Easier to understand is like this:
好吧,我将在这里扩展答案,因为很多来到这里的人都想用空格分割字符串。它是这样完成的:
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:
如果您要导入或者代码中有一个数组(字符串类型)并且必须将其转换为 arraylist(当然是字符串),那么使用集合会更好。像这样:
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:
您可以使用:
您首先应该问自己是否真的需要 ArrayList。很多时候,您将根据附加条件来过滤列表,而 Stream 是完美的选择。您可能想要一套;你可能想通过另一个正则表达式等来过滤它们。顺便说一下,Java 8 提供了这个非常有用的扩展,它适用于任何
CharSequence
:https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-。由于您根本不需要该数组,因此避免创建它:You could use:
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:这是在 Kotlin 中使用 Gson
This is using Gson in Kotlin
如果您想将字符串转换为ArrayList,请尝试以下操作:
但我在您的示例中看到一个字符串数组,因此如果您想将字符串数组< /strong> 到 ArrayList 使用这个:
If you want to convert a string into a ArrayList try this:
But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:
让我们提出一个问题:反转字符串。我将使用stream().collect() 来完成此操作。但首先我会将字符串更改为 ArrayList 。
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 .
我推荐使用 StringTokenizer,非常高效
I recommend use the StringTokenizer, is very efficient
如果您使用的是番石榴(您应该使用),请参阅 effective java item #15 ):
If you're using guava (and you should be, see effective java item #15):