List轉換成String字串三種方式
阿新 • • 發佈:2021-10-18
List轉換成String字串思路分析:
1.List轉化成String[],再通過String[]陣列遍歷拼接成String字串;
2.List轉化成String存到StringBuffer中,再通過StringButter中的append()方法拼接成String字串;
注意:StringBuffer字串變數、StringBuilder字串變數在方式二和方式三種可以把StringBuffer換成StringBuilder
方式一:
/*
* List轉換成String字串
* 方式一:
* 分析:List轉化成String[],再通過String[]陣列遍歷拼接成String字串
*
* List內容:[laoyi, laoer, laosan]
* 結果:laoyi,laoer,laosan
* */
@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
@Test
public void listToString01(){
List list = new ArrayList();
list.add("laoyi");
list.add("laoer");
list.add("laosan");
System.out.println("List陣列:"+list);
if(list == null && list.size() == 0){
System.out.println("list中的內容為空!");
}else{
String[] strArrStrings = new String[list.size()];
String resultString = "";
for(int i=0;i<=list.size()-1;i++){
strArrStrings[i] = (String) list.get(i);
}
for(int j=0;j<=strArrStrings.length-1;j++){
if(j < strArrStrings.length-1){
resultString += strArrStrings[j] + ",";
}else{
resultString += strArrStrings[j];
}
}
System.out.println("最後拼接的字串:" + resultString);
}
}
/*
* List轉換成String字串
* 方式二:
* 分析:List轉化成String存到StringBuilder中,再通過StringBuilder中的append()方法拼接成String字串
* List內容:[laoyi, laoer, laosan]
* 結果:laoyi,laoer,laosan
* */
@SuppressWarnings({ "unused" })
@Test
public void listToString03(){
List<String> list = new ArrayList<>();
list.add("laoyi");
list.add("laoer");
list.add("laosan");
if(null ==list && list.size()<=0){
System.out.println("list內容為空!");
}else{
StringBuilder sb = new StringBuilder();
String resultString = "";
for(int i=0;i<list.size();i++){
if(i<list.size()-1){
sb.append(list.get(i));
sb.append(",");
}else{
sb.append(list.get(i));
}
}
resultString = sb.toString();
System.out.println("最後拼接的字串結果:" + resultString);
}
}
/*
* List轉換成String字串
* 方式三:
* 分析:List轉化成String存到StringBuffer中,再通過StringButter中的append()方法拼接成String字串
*
* List內容:[laoyi, laoer, laosan]
* 結果:laoyi,laoer,laosan
* */
@SuppressWarnings({ "unused" })
@Test
public void listToString02(){
List<String> list = new ArrayList<>();
list.add("laoyi");
list.add("laoer");
list.add("laosan");
if(null ==list && list.size()<=0){
System.out.println("list內容為空!");
}else{
StringBuilder sb = new StringBuilder();
String resultString = "";
boolean flag = false;
for(String str : list){
if(flag){
sb.append(",");
}else{
flag = true;
}
sb.append(str);
}
resultString = sb.toString();
System.out.println("最後拼接的字串結果:" + resultString);
}
}
本文來自部落格園,作者:我是一個小倉鼠,轉載請註明原文連結:https://www.cnblogs.com/yongyuankuaile/p/15420235.html