数据类型(⼀)之List转换成String字符串三种⽅式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) (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.(i));
sb.append(",");
}else{
sb.(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);
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。