How to convert comma-separated String to List?

前端 未结 24 1997
你的背包
你的背包 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:36

    There is no built-in method for this but you can simply use split() method in this.

    String commaSeparated = "item1 , item2 , item3";
    ArrayList<String> items = 
    new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));
    
    0 讨论(0)
  • 2020-11-22 17:37

    This code will help,

    String myStr = "item1,item2,item3";
    List myList = Arrays.asList(myStr.split(","));
    
    0 讨论(0)
  • 2020-11-22 17:39
    List<String> items= Stream.of(commaSeparated.split(","))
         .map(String::trim)
         .collect(toList());
    
    0 讨论(0)
  • 2020-11-22 17:39

    An example using Collections.

    import java.util.Collections;
     ...
    String commaSeparated = "item1 , item2 , item3";
    ArrayList<String> items = new ArrayList<>();
    Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
     ...
    
    0 讨论(0)
  • 2020-11-22 17:39
    List commaseperated = new ArrayList();
    String mylist = "item1 , item2 , item3";
    mylist = Arrays.asList(myStr.trim().split(" , "));
    
    // enter code here
    
    0 讨论(0)
  • 2020-11-22 17:39
    List<String> items = Arrays.asList(s.split("[,\\s]+"));
    
    0 讨论(0)
提交回复
热议问题