How to convert comma-separated String to List?

前端 未结 24 2355
你的背包
你的背包 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: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 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 list = new LinkedList<>(col);
    

提交回复
热议问题