如何将字符串转换为ArrayList?

发布于 2024-12-04 03:05:51 字数 120 浏览 2 评论 0原文

在我的字符串中,我可以有任意数量的以逗号分隔的单词。我希望将每个单词添加到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

慢慢从新开始 2024-12-11 03:05:51

尝试类似

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));

演示:

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]

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]
毁梦 2024-12-11 03:05:51
 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());
 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());
残疾 2024-12-11 03:05:51

在 Java 9 中,使用 List#of,它是一个不可变列表静态工厂方法,变得更加简单。

 String s = "a,b,c,d,e,.........";
 List<String> lst = List.of(s.split(","));

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(","));
旧时模样 2024-12-11 03:05:51

选项1:

List<String> list = Arrays.asList("hello");

选项2

List<String> list = new ArrayList<String>(Arrays.asList("hello"));

在我看来,选项1更好,因为

  1. 我们可以将创建的ArrayList对象数量从2个减少到1个。 asList 方法创建并返回一个 ArrayList 对象。
  2. 它的性能要好得多(但它返回一个固定大小的列表)。

请参阅文档 这里

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

淡莣 2024-12-11 03:05:51

比较容易理解的是这样的:

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

Easier to understand is like this:

String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
め七分饶幸 2024-12-11 03:05:51

好吧,我将在这里扩展答案,因为很多来到这里的人都想用空格分割字符串。它是这样完成的:

List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));

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+")));
霓裳挽歌倾城醉 2024-12-11 03:05:51

如果您要导入或者代码中有一个数组(字符串类型)并且必须将其转换为 arraylist(当然是字符串),那么使用集合会更好。像这样:

String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then

List allEds = new ArrayList(); Collections.addAll(allEds, array1);

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);
猫九 2024-12-11 03:05:51

您可以使用:

List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());

您首先应该问自己是否真的需要 ArrayList。很多时候,您将根据附加条件来过滤列表,而 Stream 是完美的选择。您可能想要一套;你可能想通过另一个正则表达式等来过滤它们。顺便说一下,Java 8 提供了这个非常有用的扩展,它适用于任何 CharSequencehttps://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-。由于您根本不需要该数组,因此避免创建它:

// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);

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);
野心澎湃 2024-12-11 03:05:51

这是在 Kotlin 中使用 Gson

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

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])
初懵 2024-12-11 03:05:51

如果您想将字符串转换为ArrayList,请尝试以下操作:

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

但我在您的示例中看到一个字符串数组,因此如果您想将字符串数组< /strong> 到 ArrayList 使用这个:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
        stringList.add(s);
    }
    return stringList;
}

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;
}
↙温凉少女 2024-12-11 03:05:51

让我们提出一个问题:反转字符串。我将使用stream().collect() 来完成此操作。但首先我会将字符串更改为 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
*/

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
*/
疏忽 2024-12-11 03:05:51

我推荐使用 StringTokenizer,非常高效

     List<String> list = new ArrayList<>();

     StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
     while (token.hasMoreTokens()) {
           list.add(token.nextToken());
     }

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());
     }
清浅ˋ旧时光 2024-12-11 03:05:51

如果您使用的是番石榴(您应该使用),请参阅 effective java item #15 ):

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

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

ImmutableList<String> list = ImmutableList.copyOf(s.split(","));
雅心素梦 2024-12-11 03:05:51
String value = "java spring springboot microservices";

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

ArrayList<String> listValue = new ArrayList<>(Arrays.asList(value.split(" "));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文