How to convert comma-separated String to List?

前端 未结 24 1993
你的背包
你的背包 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:21
    List<String> items = Arrays.asList(commaSeparated.split(","));
    

    That should work for you.

    0 讨论(0)
  • 2020-11-22 17:22
    ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>(); 
    String marray[]= mListmain.split(",");
    
    0 讨论(0)
  • 2020-11-22 17:24

    You can first split them using String.split(","), and then convert the returned String array to an ArrayList using Arrays.asList(array)

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

    Two steps:

    1. String [] items = commaSeparated.split("\\s*,\\s*");
    2. List<String> container = Arrays.asList(items);
    0 讨论(0)
  • 2020-11-22 17:28

    You can do it as follows.

    This removes white space and split by comma where you do not need to worry about white spaces.

        String myString= "A, B, C, D";
    
        //Remove whitespace and split by comma 
        List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));
    
        System.out.println(finalString);
    
    0 讨论(0)
  • 2020-11-22 17:29

    String -> Collection conversion: (String -> String[] -> Collection)

    //         java version 8
    
    String str = "aa,bb,cc,dd,aa,ss,bb,ee,aa,zz,dd,ff,hh";
    
    //          Collection,
    //          Set , List,
    //      HashSet , ArrayList ...
    // (____________________________)
    // ||                          ||
    // \/                          \/
    Collection<String> col = new HashSet<>(Stream.of(str.split(",")).collect(Collectors.toList()));
    

    Collection -> String[] conversion:

    String[] se = col.toArray(new String[col.size()]);
    

    String -> String[] conversion:

    String[] strArr = str.split(",");
    

    And Collection -> Collection:

    List<String> list = new LinkedList<>(col);
    
    0 讨论(0)
提交回复
热议问题