编程语言
首页 > 编程语言> > java将list转为逗号隔开字符串

java将list转为逗号隔开字符串

作者:互联网

1.只要不为空,就在后面添加逗号,最后再用subString()函数截取,去掉最后一位的逗号
List<String> test = new ArrayList<>();
String testStrings = "";
test.add("test1");
test.add("test2");
test.add("test3");

for(String object : test){
  if(object != null){
    testStrings +=object + ",";    
  }
}
if(testStrings.length > 0){
  testStrings = testStrings.substring(0,testStrings.length() -1);
}

2.通过StringUtils的join函数直接获取逗号隔开字符串
List<String> test = new ArrayList<>();
String testStrings = "";
test.add("test1");
test.add("test2");
test.add("test3");

String join = StringUtils.join(test,",");
System.out.println(join);

3.通过流转换
String newStr = exList.stream().collect(Collectors.joining(",")))
4.将逗号连接的字符串转成字符数组:
通过String的split函数可以实现

String aaa = "aa,bb,cc";
String[] split = aaa.split(",");

标签:java,String,list,testStrings,逗号,add,test,join
来源: https://www.cnblogs.com/fuqian/p/16612802.html