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函数直接获取逗号隔开字符串
import com.alibaba.nacos.common.utils.StringUtils;
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(",");

posted @ 2021-09-13 16:50  寒冷的雨呢  阅读(7952)  评论(0编辑  收藏  举报