How to convert comma-separated String to List?

前端 未结 24 1992
你的背包
你的背包 2020-11-22 16:58

Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for t

相关标签:
24条回答
  • 2020-11-22 17:13

    Same result you can achieve using the Splitter class.

    var list = Splitter.on(",").splitToList(YourStringVariable)
    

    (written in kotlin)

    0 讨论(0)
  • 2020-11-22 17:14

    There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:

    String  commaSeparated = "item1 , item2 , item3";
    List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
                                                 .collect(Collectors.toList());
    List<String> result2 = Stream.of(commaSeparated.split(" , "))
                                                 .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 17:16

    I usually use precompiled pattern for the list. And also this is slightly more universal since it can consider brackets which follows some of the listToString expressions.

    private static final Pattern listAsString = Pattern.compile("^\\[?([^\\[\\]]*)\\]?$");
    
    private List<String> getList(String value) {
      Matcher matcher = listAsString.matcher((String) value);
      if (matcher.matches()) {
        String[] split = matcher.group(matcher.groupCount()).split("\\s*,\\s*");
        return new ArrayList<>(Arrays.asList(split));
      }
      return Collections.emptyList();
    
    0 讨论(0)
  • 2020-11-22 17:20

    In Kotlin if your String list like this and you can use for convert string to ArrayList use this line of code

    var str= "item1, item2, item3, item4"
    var itemsList = str.split(", ")
    
    0 讨论(0)
  • 2020-11-22 17:21

    Convert comma separated String to List

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

    The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace which will place the words into the list and collapse any whitespace between the words and commas.


    Please note that this returns simply a wrapper on an array: you CANNOT for example .remove() from the resulting List. For an actual ArrayList you must further use new ArrayList<String>.

    0 讨论(0)
  • 2020-11-22 17:21

    Here is another one for converting CSV to ArrayList:

    String str="string,with,comma";
    ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
    for(int i=0;i<aList.size();i++)
    {
        System.out.println(" -->"+aList.get(i));
    }
    

    Prints you

    -->string
    -->with
    -->comma

    0 讨论(0)
提交回复
热议问题