java将list转换为字符串_List转换成String字符串三种方式

List转换成String字符串思路分析: 1.List转化成String[],再通过String[]数组遍历拼接成String字符串; 2.List转化成String存到StringBuffer中,再通过StringButter中的append()方法拼接成String字符串; 注意:StringBuffer字符串变量、StringBuilder字符串变量在方式二和方式三种可以把StringBuffer换成StringBuilder,但需要了解二者之间的区别,网址:https://blog.csdn.net/u013131716/article/details/99628104

package com.test01.listtostring;

import java.util.ArrayList;

import java.util.List;

import org.junit.Test;

public class ListToStringTest {

/*

* 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 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

if(i

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 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);

}

}

}

你可能感兴趣的:(java将list转换为字符串)