【问题标题】:How to convert String into ArrayList properly?如何正确将 String 转换为 ArrayList?
【发布时间】:2021-10-21 14:43:27
【问题描述】:

我想将此String 转换为ArrayList

字符串

["one","two","three"]

我用过这个方法

List<String> logopath = Arrays.asList(pos.split("\\s*,\\s*"));

我从logopath得到这个输出

0 = "["one""
1 = ""two""
2 = ""three"]"

但我希望logopath 的输出是这样的:

0 = "one"
1 = "two"
2 = "three"

【问题讨论】:

    标签: java android arrays string list


    【解决方案1】:

    您的字符串实际上是有效的 JSON,所以我建议在这里使用 JSON 解析器:

    String input = "[\"one\",\"two\",\"three\"]";
    Gson gson = new Gson();
    JsonArray items = gson.fromJson(input, JsonArray.class);
    List<String> list = new ArrayList<>();
    for (JsonElement item : items) {
        String num = item.getAsString();
        list.add(num);
    }
    
    System.out.println(list);
    

    【讨论】:

    • 非常感谢,但 items 是 JsonArray 但我需要 List 或 Arraylist
    • 这个较短的版本可以在 Java 16 中使用吗? List&lt;String&gt; list = new Gson().fromJson( input, JsonArray.class ).stream().map( JsonElement :: getAsString ).toList()
    • @Basil 通常我会提供您的流版本(或类似的版本),但我是用手机接听的,因此无法对其进行测试。
    • @BasilBourque 谢谢,这基本上也可以,但我使用 java 1.7,所以我认为我不能使用流。
    【解决方案2】:

    可以如下实现,

    String input[] = {"one","two","three"};
        List<String> arrList = new ArrayList<>();
    
        for(String s:input){
    
            arrList.add(s);
        }
        System.out.print(arrList);
    

    【讨论】:

    • 谢谢,但我的字符串只是 string 而不是 string[] ,所以我无法应用它。
    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 2021-02-21
    • 1970-01-01
    • 2012-06-06
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    相关资源
    最近更新 更多