逗號分隔的字符串與List互轉


 

將逗號分隔的字符串轉換為List

// 將逗號分隔的字符串轉換為List
String str = "a,b,c";
// 1.使用JDK,逗號分隔的字符串-->數組-->list
List<String> result = Arrays.asList(str.split(","));
// 2.使用Apache Commons的StringUtils
List<String> result1 = Arrays.asList(StringUtils.split(str, ","));
// 3.通過遍歷
String[] strings = str.split(",");
List<String> result2 = new ArrayList<String>();
for (String string : strings) {
    result2.add(string);
}

 

將List轉換為逗號分隔的字符串

// 將List轉換為逗號分隔的字符串
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
// 1.使用Apache Commons的StringUtils
String str1 = StringUtils.join(list.toArray(), ",");
// 2.通過遍歷
StringBuffer str2 = new StringBuffer();
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = (String) iterator.next();
    str2.append(string);
    if(iterator.hasNext()){
        str2.append(","); 
    }
}

 

Apache Commons的StringUtils下載: http://download.csdn.net/download/xc_oo0/9988044

http://commons.apache.org/proper/commons-lang/download_lang.cgi

參考文章: https://www.cnblogs.com/hui-blog/p/6375174.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM